a lambda in a function
Luigi Ballabio
ballabio at mac.com
Thu Dec 13 04:34:38 EST 2001
At 10:12 PM 12/12/01 +0000, Fred Clare wrote:
>Why does interpreting the five lines:
>def func():
> x = 1
> add_one = lambda i: i+x
> j = add_one(100)
>func()
>
>Give me:
>
> Traceback (most recent call last):
> File "test.py", line 6, in ?
> func()
> File "test.py", line 4, in func
> j = add_one(100)
> File "test.py", line 3, in <lambda>
> add_one = lambda i: i+x
> NameError: There is no variable named 'x'
It's a scope thing. The scope of the lambda doesn't "see" the scope of the
enclosing function---only the global scope.
You can fix it in two ways: the first is to import x into the lambda scope
by means of a default parameter; this works in all versions of Python:
def f():
x = 1
add_one = lambda i,x=x: i+x
j = add_one(100)
The second works for Python 2.1 and above: the interpreted lets you declare
that you want the scope of the function to be visible from the lambda. The
directive you have to add is:
from __future__ import nested_scopes
def f():
x = 1
add_one = lambda i: i+x # it will work now
j = add_one(100)
You'll be happy to know that starting from Python 2.2 the above is the
default behavior---i.e., had you used Python 2.2b2, your code would have
ran as expected.
Bye,
Luigi
More information about the Python-list
mailing list