3

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?

Community
  • 1
  • 1
etuardu
  • 5,066
  • 3
  • 46
  • 58
  • 2
    does http://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture-in-python answer your question? looks a bit like a dupe – ThiefMaster Nov 08 '12 at 11:39
  • @ThiefMaster: it does, I see the same technique I used in my answer here proposed there. – Martijn Pieters Nov 08 '12 at 11:40
  • D'oh... altough the question was not exactly the same, there was indeed an answer for my question there. Anyway it isn't the accepted one and the question was about understanding closures instead of reaching a precise target. – etuardu Nov 08 '12 at 11:47

1 Answers1

5

You could set the value of txt as a default value to a keyword argument:

dictfun = dict()
for txt in ("a", "b", "c"):
    dictfun[txt] = lambda txt=txt: "function " + txt
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343