problem with lambda / closures
Terry Reedy
tjreedy at udel.edu
Tue Dec 1 16:50:33 EST 2009
Jussi Piitulainen wrote:
> Terry Reedy writes:
>
>> definitions. Lambda expressions create functions just like def
>> statements and are not closures and do not create closure unless
>> nested within another function definition. Thinking otherwise is
>
> Seems quite closed in the top level environment to me:
>
> Python 2.3.4 (#1, Jul 16 2009, 07:03:37)
> >>> k = 'outer'
> >>> f = lambda : k
> >>> def test():
> ... k = 'inner'
> ... return f()
> ...
> >>> test()
> 'outer'
> >>> k = 'thing'
> >>> test()
> 'thing'
I used closure in the same sense as the OP, who would have expected the
last result to be 'outer', not 'thing'. Runtime lookup in the lexically
defined global namespace is normal function behavior, not special
closure behavior as most people mean is.
Terry Jan Reedy
More information about the Python-list
mailing list