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

Stephan schenette at gmail.com
Thu Sep 1 03:39:24 EDT 2011


thanks Reza,

Can you think of any reason why I would want a deferred in my scenerio?

Stephan

On Thu, Sep 1, 2011 at 12:31 AM, Reza Lotun <rlotun at gmail.com> wrote:
> 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
>
>
> _______________________________________________
> Twisted-web mailing list
> Twisted-web at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web
>
>



More information about the Twisted-web mailing list