Not understanding lamdas and scoping

castironpi at gmail.com castironpi at gmail.com
Wed Mar 26 22:09:54 EDT 2008


On Mar 26, 5:03 pm, Joshua Kugler <jkug... at bigfoot.com> wrote:
> George Sakkis wrote:
> > On Mar 26, 5:02 pm, Joshua Kugler <jkug... at bigfoot.com> wrote:
>
> >> I am trying to use lamdba to generate some functions, and it is not
> >> working
> >> the way I'd expect.  The code is below, followed by the results I'm
> >> getting.  More comments below that.
>
> >> (...)
>
> >> So, is there some scoping issue with lambda
> >> that I'm not seeing?
>
> > Yes; it's not related to lambda though but to closures (whether
> > defined as lambdas or regular functions). See for example

I saw it somewhere, maybe recipies.

>>> funs= []
>>> for i in range( 2 ):
...     def f(): pass
...     print( f )
...     funs.append( f )
...
<function f at 0x00B6B6A8>
<function f at 0x00B6BB70>
>>> funs[0]
<function f at 0x00B6B6A8>
>>> funs[1]
<function f at 0x00B6BB70>
>>>

You also have:

>>> partial( lambda a: 0 )
<functools.partial object at 0x00C1C1E0>
>>> _( 1 )
0
>>>

and partial use cell, so it binds values.  But:

>>> a= (1,2)
>>> c= lambda b: a[b]
>>> c(0)
1
>>> a= (2,2)
>>> c(0)
2
>>>

Lambda is late-bound by name.




More information about the Python-list mailing list