problem with lambda / closures

inhahe inhahe at gmail.com
Mon Nov 30 12:21:58 EST 2009


On Mon, Nov 30, 2009 at 10:54 AM, Benjamin Kaplan
<benjamin.kaplan at case.edu> wrote:
>
> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Well default arguments isn't the only way - and *sometimes* it's not
workable.  Another way to make closures in Python is to define the
function a within function b which returns function a and in your loop
call function b.

i guess if you wanted to do that purely with lambas (outside of using
default arguments like i=i) you'd have to do something like

a = []
for x in xrange(10):
  a.append((lambda x: lambda: x)(x))

never tried that though..



More information about the Python-list mailing list