[Twisted-web] using @defer.inlineCallbacks and yield correctly

Reza Lotun rlotun at gmail.com
Thu Sep 1 03:31:27 EDT 2011


Hi Stephan,


> from what I understand  @defer.inlineCallbacks is used to defer a
> async callback function like how i'm using CallLater below, but where
> is the yield supposed to be? and how should the below code change?
>
>
The advantage defer.inlineCallbacks offers is allowing one to wait on the
result of a deferred inline, without having nested blocks and closures.

So a generic example could be:

Without inlinecallbacks:

def my_func():
    d = func_returnning_deferred()
    def handle_result(r):
        # do something with r
        ..
    d.addCallback(handle_result)
    return d

With inlineCallbacks:

@defer.inlineCallbacks
def my_func():
     r = yield func_returning_deferred()
     # do stuff with r

You can see that we don't have to have a nested block with an addCallback.
Here the yield returns the result that we'd get in our callback function (an
likewise if the errBack fired we've have to wrap that line in a try/except
to handle it).

Keep in mind however that @defer.inlineCallbacks can only wrap generators
(functions with a yield statement in it)


>    def connectionMade(self):
>        logging.debug("connection made timeout = %d", self.timeout)
>        @defer.inlineCallbacks
>        def onTimer():
>            logging.debug("timeout triggered")
>            self.firefoxProcess.handleProcessTimedOut()
>            self.killProcessIfAlive()
>        d = reactor.callLater(self.timeout, onTimer)


You can see here that onTimer is not a generator (there's no yield) so
defer.inlineCallbacks cannot be applied to it. Also, based on what you're
doing you don't need it (i.e. you can just remove it).

Keep in mind that callLater doesn't return a deferred - it just schedules
onTimer to be called at a later time, which makes sense for what you are
doing. If for some reason you want a deferred, I'd take a look at
twisted.internet.task.deferLater.

Hope that helps,
Reza

-- 
Reza Lotun
mobile: +44 (0)7521 310 763
email:  rlotun at gmail.com
work:   rlotun at twitter.com
@rlotun
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-web/attachments/20110901/e8879745/attachment.htm 


More information about the Twisted-web mailing list