Weird lambda behavior

Diez B. Roggisch deets at nospam.web.de
Wed Apr 22 11:50:32 EDT 2009


Rüdiger Ranft wrote:

> Hi all,
> 
> I want to generate some methods in a class using setattr and lambda.
> Within each generated function a name parameter to the function is
> replaced by a string constant, to keep trail which function was called.
> The problem I have is, that the substituted name parameter is not
> replaced by the correct name of the function, but by the last name the
> for loop has seen.

Python's closures don't capture the values, but only the names they contain
when they are created. So whatever value is bound to that name as last is
used.

to overcome this, you need to create another closure or bind the value to a
name local to the created function via named arguments:

>>> for f in [lambda i=i: i**2 for i in xrange(10)]:
...     f()
...
0
1
4
9
16
25
36
49
64
81


Diez







More information about the Python-list mailing list