problem with lambda / closures

Louis Steinberg lou at cs.rutgers.edu
Mon Nov 30 10:09:07 EST 2009


I figured out the answer to my own query.  In the original example  
(see below), there was only one binding for k, which was shared by  
all the closures, so they all saw the same value.  Consider:


def fie2(k):
     return lambda: fie3(k)

def fie3(m):
     print m

def fie1(j):
     return fie2(j)


l=map(fie1,[1,2,3])

map(lambda f:f(), l)


This prints
1
2
3
because each lambda has its own binding of k.


On Nov 30, 2009, at 7:35 AM, Louis Steinberg wrote:


> I have run into what seems to be a major bug, but given my short  
> exposure to Python is probably just a feature:
>
> running
> Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
> [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
>
> with file foo.py containing:
>
> ============================== clip here ============
> def p(d):
>     print d
>
>
> l=[ ]
> for k in [1,2,3]:
>     l.append(lambda : p(k))
>
> for f in l:
>     f()
>
> ============================== clip here ============
> I get output
> 3
> 3
> 3
> instead of
> 1
> 2
> 3
> which I would expect.  Can anyone explain this or give me a  
> workaround?  Thank you
>
>
>
>




More information about the Python-list mailing list