[Tutor] Bitten by lexical closures
Chad Crabtree
flaxeater at gmail.com
Wed May 3 20:24:45 CEST 2006
Are you just trying to make a continuation?
On 5/3/06, Igor <igor at c-base.org> wrote:
> 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 at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list