closures and dynamic binding

Aaron "Castironpi" Brady castironpi at gmail.com
Sun Sep 28 00:43:15 EDT 2008


Hello all,

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

I guess I can accept this part so far, though it took a little getting
used to.  I'm writing some code and found the following workaround,
but I don't think it should give different results.  Maybe I'm not
understanding some of the details of closures.

>>> 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?



More information about the Python-list mailing list