unexpected behaviour of lambda expression

Duncan Booth duncan.booth at invalid.invalid
Mon Oct 9 03:56:16 EDT 2006


leonhard.vogt at gmx.ch wrote:

>>>> f = lambda x: s
...
>>>> f(None)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 1, in <lambda>
> NameError: global name 's' is not defined
> 
> It seems to me, that f is referencing the name s instead of the string
> object bound to it

Of course it is. Why would you expect a function to lookup its global 
variables before it is called? Remember "f = lambda x: s" is just a 
confusing way to write:

def f(x):
    return s



More information about the Python-list mailing list