closures and dynamic binding
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Sun Sep 28 02:14:01 EDT 2008
On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote:
> To me, this is a somewhat unintuitive behavior. I want to discuss the
> parts of it I don't understand.
>
>>>> f= [ None ]* 10
>>>> for n in range( 10 ):
> ... f[ n ]= lambda: n
> ...
>>>> f[0]()
> 9
>>>> f[1]()
> 9
`n` is looked up at the time ``f[0]`` is called. At that time it is
bound to 9.
>>>> f= [ None ]* 10
>>>> for n in range( 10 ):
> ... f[ n ]= (lambda n: ( lambda: n ) )( n ) ...
>>>> f[0]()
> 0
>>>> f[1]()
> 1
>
> Which is of course the desired effect. Why doesn't the second one just
> look up what 'n' is when I call f[0], and return 9?
It *does* look up `n` at the time you call ``f[0]`` but this time it's
the local `n` of the outer ``lambda`` function and that is bound to
whatever the function was called with. At the time it was called the
global `n` was bound to 0. Maybe it get's more clear if you don't name
it `n`:
In [167]: f = [None] * 10
In [168]: for n in xrange(10):
.....: f[n] = (lambda x: lambda: x)(n)
.....:
In [169]: f[0]()
Out[169]: 0
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list