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

Bob Ippolito bob at redivi.com
Wed Dec 3 21:38:50 EST 2003

On Dec 3, 2003, at 8:48 PM, Jonathan Simms wrote:

> 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)
>     d.callback(result)
> the little trick I figured out today is as follows:
> def aLongWait(stuff):
>     d = defer.Deferred()
>     def _():
>          result = doSomeStuffHere(stuff)
>          d.callback(result)
>     reactor.callLater(0, _)
>     return d

That's still totally wrong.  You either need to defer doSomeStuffHere 
to a thread (reactor.callInThread), or refactor "doSomeStuffHere" into 
an iterator that only does a little bit each call.. and then call it 
once a runloop until it's done, and when it's done you do the callback 
with the result.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2357 bytes
Desc: not available
Url : http://twistedmatrix.com/pipermail/twisted-python/attachments/20031203/5554079c/attachment.bin 

More information about the Twisted-Python mailing list