[Twisted-web] using @defer.inlineCallbacks and yield correctly
schenette at gmail.com
Thu Sep 1 03:39:24 EDT 2011
Can you think of any reason why I would want a deferred in my scenerio?
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
> return d
> With 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)
>> def onTimer():
>> logging.debug("timeout triggered")
>> 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
> Hope that helps,
> Reza Lotun
> mobile: +44 (0)7521 310 763
> email: rlotun at gmail.com
> work: rlotun at twitter.com
> Twisted-web mailing list
> Twisted-web at twistedmatrix.com
More information about the Twisted-web