a lambda in a function

Tim Daneliuk tundra at tundraware.com
Wed Dec 12 17:49:06 EST 2001


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'
> 
> while interpreting the three lines:
> 
> x = 1
> add_one = lambda i: i+x
> j = add_one(100)
> 
> works just fine?

This is apparently scope related because this works:

def func():
	global x
 	x = 1
 	add_one = lambda i: i+x
 	return add_one(100)

When I run your version under PythonWin, I get the following warning
after defining func():

<interactive input>:1: SyntaxWarning: local name 'x' in 'func' shadows use of 'x'
as global in nested scope 'lambda'

-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com



More information about the Python-list mailing list