problem with lambda / closures

Benjamin Kaplan benjamin.kaplan at case.edu
Mon Nov 30 10:54:47 EST 2009


On Monday, November 30, 2009, Louis Steinberg <lou at cs.rutgers.edu> 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
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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.



More information about the Python-list mailing list