Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twisted (Python) - what is the difference between cooperate and coiterate?

Tags:

python

twisted

The docs here http://twistedmatrix.com/documents/current/api/twisted.internet.task.html#cooperate suggest that the difference is that cooperate returns a CooperativeTask whereas coiterate returns a Deferred (evidenced by my own tests, not specified in docs). I've invested the weekend learning the basics of Twisted, so I understand what a Deferred is and I've been a good boy sending my blocking code off to threads/processes. I understand coiterate goes as fast as Twisted allows it, whereas LoopingCall tries to fire at the selected interval.

My hunch is that cooperate() tasks are done inside CooperativeTask objects and coiterate() within Deferred objects. If someone can summarize the differences in behavior between cooperate and coiterate I'd appreciate it.

like image 655
pagga Avatar asked Apr 10 '12 02:04

pagga


1 Answers

Almost, but not exactly. cooperate is a slightly newer API than coiterate. cooperate is generally just a slightly better version of coiterate and you pretty much always want to use it. Returning a CooperativeTask confers two benefits. First, you can pause and resume the task without stopping it, and second, you can generate multiple Deferreds that notify you of when the task is done without interfering with each other, rather than just the one.

Both coiterate and cooperate produce a CooperativeTask under the hood, and both use a very short interval LoopingCall as their default scheduler. If you want to use a different task scheduler you can always instantiate your own Cooperator.

(By the way, if there's no doc bug yet for the fact that coiterate returns a Deferred, please file one.)

like image 106
Glyph Avatar answered Oct 04 '22 19:10

Glyph