[Tutor] Bitten by lexical closures

Igor igor at c-base.org
Wed May 3 14:00:13 CEST 2006


Hi.

And I thought I understood python pretty well. Until I got hit by this:

>>> def f(x):
...   print x

>>> cb = [lambda :f(what) for what in "1234"]
>>> for c in cb:c()
4
4
4
4

And even this works

>>> what = "foo"
>>> for c in cb:c()
foo
foo
foo
foo

I expected the output to be 1 2 3 4. Now I understand the cookbook
recipe for currying:
def curry(func, *args, **kwds):
    def callit(*moreargs, **morekwds):
        kw = kwds.copy()
        kw.update(morekwds)
        return func(*(args+moreargs), **kw)
    return callit

cb = [curry(f,what) for what in "1234"]

gives the right functions. 

Regards,
Igor


More information about the Tutor mailing list