problem with lambda / closures

Jussi Piitulainen jpiitula at ling.helsinki.fi
Mon Nov 30 18:39:00 CET 2009


Benjamin Kaplan writes:
> On Monday, November 30, 2009, 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
> 
> I don't know if anyone considers python's incomplete implementation
> of closures a "feature" but it's documented so it's not really a bug
> either. I believe there is a trick with default arguments to get
> this to work, but I don't use lambdas enough to remember it.

That trick has been shown in some branch of the present thread.

Here's a non-trick solution, which I saved in file quux.py:

def p(d):
    print d

l=[]
for k in [1,2,3]:
    l.append((lambda k : lambda : p(k))(k))

for f in l:
    f()


Python 2.3.4 (#1, Jul 16 2009, 07:03:37) 
[GCC 3.4.6 20060404 (Red Hat 3.4.6-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import quux
1
2
3
>>> 



More information about the Python-list mailing list