spyce
home
license
community
download
examples
resources
wishlist
contrib (@sf)
documentation
intro
lang
runtime
modules
tags
install
exits
sourceforge
statistics
freshmeat

transparent transparent transparent
Documentation - Language
[[ Spyce ]]
Python Server Pages
by Rimon Barr

Prev: 2.6 - Python Expressions Up: 2 - Language Next: 2.8 - ASP/JSP syntax

2.7. Spyce Lambdas

Syntax: [[spy [params] : spyce lambda code ]]
or: [[spy! [params] : spyce lambda code ]]

A nice feature of Spyce is that Spyce scripts are first-class members of the language. In other words, you can create a Spyce lambda (or function) in any of the Spyce Python elements (statements, chunks and expressions). These can then be invoked like regular Python functions, stored in variables for later use, or be passed around as paramaters. This feature is often very useful for templating (example shown below), and can also be used to implement more esoteric processing functionality, such as internationalization, multi-modal component frameworks and other kinds of polymorphic renderers.

It is instructive to understand how these functions are generated. The [[spy ... : ... ]] syntax is first translated during compilation into a call to the define() function spylambda module. At runtime, this call compiles the Spyce code at the point of definition, and returns a function. While the invocation of a Spyce lambda is reasonably efficient, it is certainly not as fast as a regular Python function invocation. The spycelambda can be memoized (explained in the spylambda module section) by using the [[spy! ... : ... ]] syntax. However, even with this optimization one should take care to use Python lambdas and functions when the overhead of Spyce parsing and invocation is not needed.

Note that Spyce lambdas do not currently support nested variable scoping, nor default parameters. The global execution context (specifically, Spyce modules) of the Spyce lambda is defined at the point of its execution.

examples/spylambda.spy
[[
  # table template
  table = [[spy! title, data: 
    <table>
      <tr>
        [[for cell in title: {]]
          <td><b>[[=cell]]</b></td>
        [[}]]
      </tr>
      [[for row in data: {]]
        <tr>
          [[for cell in row: {]]
            <td>[[=cell]]</td>
          [[}]]
        </tr>
      [[}]]
    </table> 
  ]]

  # table information
  title = ['Country', 'Size', 'Population', 'GDP per capita']
  data = [
    [ 'USA', '9,158,960', '280,562,489', '$36,300' ],
    [ 'Canada', '9,220,970', '31,902,268', '$27,700' ],
    [ 'Mexico', '1,923,040', '103,400,165', '$9,000' ],
  ]
]]

[[-- emit web page --]]
<html><body>
  [[ table(title, data) ]]
</body></html>

Run this code.
(requires Spyce-enabled web server)


Prev: 2.6 - Python Expressions Up: 2 - Language Next: 2.8 - ASP/JSP syntax


© 2002 Rimon Barr
email: rimon AT acm DOT org
Spyce Powered SourceForge Logo [[ Spyce ]]
Python Server Pages
version 1.3.10