[Twisted-Python] Deferred usage clarification

Gary Poster gary at zope.com
Sun Jun 1 18:05:02 MDT 2003


Hi.  A newbie question: I'd like a bit of clarification in Deferred 
usage.  More specifically, it would be nice if one of the examples on 
the Twisted Deferred howto page used a real blocking call rather than a 
reactor.callLater.

So, to see if I'm on the right track, I'd like to modify the third code 
example to use a sleep, to make it better parallel the first code 
snippet on the howto page.

First, here it is from the page, without modification:

-----8<-----8<-----8<-----
from twisted.internet import reactor, defer

class Getter:
     def getData(self, x):
         # this won't block
         d = defer.Deferred()
         reactor.callLater(2, d.callback, x * 3)
         return d

def printData(d):
     print d

g = Getter()
d = g.getData(3)
d.addCallback(printData)

reactor.callLater(4, reactor.stop); reactor.run()
-----8<-----8<-----8<-----

Here's my modification.  Is this the right usage?

-----8<-----8<-----8<-----
from twisted.internet import reactor, defer
import time

class Getter:
     def getData(self, x):
         # this won't block
         d = defer.Deferred()
         reactor.callLater(0, self.doWork, x, d)
         return d

     def doWork(self, x, deferred):
         # churn, churn, churn
         time.sleep(2)
         deferred.callback(x * 3)

def printData(d):
     print d

g = Getter()
d = g.getData(3)
d.addCallback(printData)

reactor.callLater(4, reactor.stop); reactor.run()
-----8<-----8<-----8<-----

Thanks!

Gary





More information about the Twisted-Python mailing list