etk
etk

Reputation: 83

twisted task.LoopingCall messes callbacks when they are defined in loop

When there are some LoopingCall task defined in loop, twisted messes callbacks and always executes last one defined

sample code:

from twisted.internet import reactor, task
from pprint import pprint

for s in [1,2]:
  task.LoopingCall(lambda: pprint(s)).start(1)

reactor.run()

response: 1 2 2 2 2 2

code without loop that works:

from twisted.internet import reactor, task
from pprint import pprint

task.LoopingCall(lambda: pprint(1)).start(1)
task.LoopingCall(lambda: pprint(2)).start(1)

reactor.run()

correct response: 1 2 1 2 1 2

Upvotes: 2

Views: 523

Answers (1)

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48325

This is a result of how scopes work in Python.

Forget about Twisted for a moment and just consider this example:

x = 1
f1 = lambda: x
x = 2
f2 = lambda: x
print f1()
print f2()

You might expect the result to be:

1
2

However, instead, it is:

2
2

The f1 and f2 functions both "close over" the same variable: x. The variable can only refer to one object at a time, and after x = 2, it refers to 2 - not 1.

Upvotes: 2

Related Questions