lambda (closure)

Lambdas can be used with map() or filter. This is demonstrated in 8.15

Lambdas can also be used to contruct closures. These are functions which refer to variables that are latched at the time when the close is created. This is how it works:

#!/usr/bin/env python

def f1(x):
    print( "f1:", x)

a = 'one'
f = lambda a=a: f1(a)
a = 'two'
g = lambda a=a: f1(a)
f()
g()

The trick is the 'a=a' argument of lambda. This way the current value of 'a' is frozen in a local variable.

Here is another example for constructing a closure:

#!/usr/bin/env python

def f1(x):
    print( "f1:", x)

def genFunc( b):    
    return lambda : f1(b)
a = 'one'
f = genFunc( a)
a = 'two'
g = genFunc( a)
f()
g()