Python really uses links, of course, but that doesn't matter in this context.
When you define a lambda (or function, since this is the same behavior), it does not evaluate the lambda expression before the runtime:
# defining that function is perfectly fine def broken(): print undefined_var broken()
Even more surprising than your lambda example:
i = 'bar' def foo(): print i foo()
In short, think dynamically: nothing is evaluated before interpretation, so your code uses the last value of m.
When he searches for m in lambda execution, m is taken from the upper region, which means that, as others have pointed out; you can work around this problem by adding another area:
def factory(x): return lambda: callback(x) for m in ('do', 're', 'mi'): funcList.append(factory(m))
Here, when a lambda is called, it looks at the lambda definition area for x. This x is a local variable defined in the body of the factory. Because of this, the value used when executing the lambda will be the value that was passed as a parameter during the factory call. And finish off!
As a note, I could define factory as factory (m) [replace x with m], the behavior will be the same. I used a different name for clarity :)
You may find that Andrej Bauer got similar problems with lambda. What is interesting about this blog is the comments in which you will learn more about closing python :)
NicDumZ Jun 02 '09 at 8:27 2009-06-02 08:27
source share