[Twisted-Python] way of dealing with returning a deferred from a method/function

Jonathan Simms slyphon at twistedmatrix.com
Wed Dec 3 20:48:56 EST 2003

This may seem obvious to everyone, but I had an insight into the use of
deferreds today. It would always confuse me, I've got a method that's
going to take quite a while to run. When something calls it, i want to
immediately return a deferred. But how to accomplish this? returns (most
frequently) come at the *end* of a function!

I was thinking about it like this (hence my confusion):

def aLongWait(stuff):		# obviously incorrect
    d = defer.Deferred()   
    return d
    result = doSomeStuffHere(stuff)

the little trick I figured out today is as follows:

def aLongWait(stuff):
    d = defer.Deferred()
    def _():
         result = doSomeStuffHere(stuff)
    reactor.callLater(0, _)
    return d

it's almost like a deferred block (in the try/except sense). It creates
a deferred that is (pretty much) guaranteed only to be called by
aLongWait(), it returns that deferred, then in the next reactor
iteration, it runs the steps that will have to wait a long time to be
processed. at the end of doSomeStuffHere() it calls back the deferred
with the result.

Neat huh?

This is going to clean up about 50% of the deferreds i use! (before i
was defining an instance variable deferred and using and resetting it if
i needed another one, which was messy)

Anyway, just adding to the collective knowledge base.

- Jonathan Simms
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : http://twistedmatrix.com/pipermail/twisted-python/attachments/20031203/a645a246/attachment.pgp 

More information about the Twisted-Python mailing list