problem using lambdas for deferred callbacks

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sun Dec 10 10:38:29 EST 2006


In <1165764662.462927.147010 at 79g2000cws.googlegroups.com>, edd wrote:

> I was hoping that the following code would print "Hello, world!", one
> character per line. But instead it prints an exclamation mark for each
> character of the string. I'm sure it's no coincidence that the last
> value of c is '!', but beyond that I don't understand what's happening.

If you call the lambda function the name `c` is looked up in the
"environment". It's not local to the function.

> # --- begin code ---
> def callback(arg):
>     print arg
> 
> funcs = []
> for c in 'Hello, world!':
>     funcs.append(lambda: callback(c))

Change this line to:

     funcs.append(lambda x=c: callback(x))

Now the `c` is bound to the default argument `x` at definition time.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list