Possible Duplicate:
What do (lambda) function closures capture in Python?
I have this python code that puts several lambda functions in a dictionary:
dictfun = dict()
for txt in ("a", "b", "c"):
dictfun[txt] = lambda: "function " + txt
Those functions just return a string with the arguments they are called with.
I expected to see an output like function a
for dictfun["a"]()
, function b
for dictfun["b"]()
and so on, but this is what I get:
>>> dictfun["a"]()
'function c'
>>> dictfun["b"]()
'function c'
>>> dictfun["c"]()
'function c'
It appears that they all evaluate txt
to the last value it was set, i.e. its current value. In a word, the variable isn't closed into the lambdas. I can even do this:
>>> txt = "a"
>>> dictfun["c"]()
'function a'
How could I close txt
into the lambda functions in order to get my expected outputs?