5 ms·
> In common Twisted programming a deferred can not fire before you add the callback since the only way a deferred can fire (for typical async work!) is through
by thristian 13y ago
> In common Twisted programming a deferred can not fire before you add the callback since the only way a deferred can fire (for typical async work!) is through the proactor (which Twisted calls the reactor) and you haven't yet returned control to the proactor.
d = Deferred()
d.callback(42)
return d
Hey, I just made a Deferred that fired before any callbacks were added! In fact, this is such a common occurrence that there's helper functions in the "defer" module to do it: defer.succeed() and defer.fail(). In particular, this sort of thing is very useful for unit-testing Deferred-based APIs.
- rdtsc 13y agoYou are right. I _think_ what they meant to say was that the deferred can only fire once. You cannot call .callback() twice. Or adding deferreds to it after it fired won't get those functions called. However, even with respect to your example, it is not idiomatic. Yes you can do anything on anything in Python. And in testing you often monkey-patch and mock things. Which doesn't mean you'd do often in production code. The idea of deferreds is to help with highly concurrent IO applications. It will be a file descriptor (socket) or a timer that will fire your callback more than often.
- lvh 13y agoThey get used quite often in production code quite often too: any time you have a synchronous implementation to an asynchronous interface. E.g. your DNS name resoltion thing may have to go query a Postgres database far away (that'd be asynchronous), but maybe it has to grab an entry from a (Python) list (that'd be synchronous).
- YZF 13y agoYes and that's why I added typical async work. From the docs "callback: Run all success callbacks that have been added to this Deferred.". Let's see your calling code to this snippet. Is it adding callbacks? Why?