parameters confuse me a lot when i using defer function with twisted.
i consider if the function’s parameter is a INT-VALUE, or other basic types besides of list and dict, it should pass-by value not reference.
from twisted.internet import defer, reactor
def deferFunc(x):
print "11111 %d" % x
d = defer.Deferred()
reactor.callLater(1, d.callback, x)
return d
@defer.inlineCallbacks
def inlineDeferFunc(x):
print "11111 %d" % x
d = defer.Deferred()
reactor.callLater(1, d.callback, x)
result = yield d
defer.returnValue(result)
def loop():
x = [1,2,3,4]
d = defer.succeed(0)
for i in x:
d.addCallback(lambda _ : inlineDeferFunc(i))
if __name__ == '__main__':
loop()
try:
reactor.run()
except:
reactor.stop()
the result is :
11111 1
11111 4
11111 4
11111 4
and the result confused me.
how can i get the right output like 1,2,3,4
like this:
note that we are copying the values in the function definition
i = i.the problem was that the
lambdagrabs the parent environment to access the variableiafter all how it would know what value it is, for performance reasons I don’t think it copies it during definition, but the parent environment keeps being updated by theforloop.here is a simple test.