The following code spits out 1
twice, I expect to see 0
and then 1
def pv(v) :
print v
def test() :
value = []
value.append(0)
value.append(1)
x=[]
for v in value :
x.append(lambda : pv(v))
return x
x = test()
for xx in x:
xx()
I expected python lambdas to bind to the reference a local variable is pointing to, behind the scene. However that does not seem to be the case. I have enountered this problem in a large system where the lambda is doing modern C++'s equavalent of a bind ('boost::bind' for example) where in such case you would bind to a smart ptr or copy contstruct a copy for the lambda.
So, how do I bind a local variable to a lambda function and have it retain the correct reference when used? I'm quite gobsmacked with the behaviour since I would not expect this from a language with a garbage collector.
The code in question looks as follows (l3_e is the variable which is causing the problem) :
for category in cat :
for l2 in cat[category].entries :
for l3 in cat[category].entries[l2].entry["sub_entries"] :
l3_e = cat[category].entries[l2].entry["sub_entries"][l3]
url = "http://forums.heroesofnewerth.com/" + l3_e.entry["url"]
self.l4_processing_status[l3_e] = 0
l3_discovery_requests.append( Request(
url, callback = lambda response : self.parse_l4(response,l3_e)))
print l3_e.entry["url"]
return l3_discovery_requests