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
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to