[Twisted-Python] Inline Callbacks

Christopher Armstrong radix at twistedmatrix.com
Fri Apr 2 00:33:51 EDT 2010


On Thu, Apr 1, 2010 at 8:20 PM, Jason J. W. Williams
<jasonjwwilliams at gmail.com> wrote:
> Would it be fair to say that when developing code that utilizes
> inlineCallbacks, your function is a generator that returns a deferred
> whose callback is the coroutine that's yielding?

It pays to be very very specific about all the different objects and
interactions going on with generators in Python and especially with
inlineCallbacks to avoid confusion.There are a couple of inaccuracies
in this statement, some which I think are just about poor wording and
some which come from misunderstanding.

In Python, there are generator functions and there are generators.
Calling a generator function returns a generator, which has next() and
send() methods. Generators do not return things, though a generator's
next() or send() methods do (I say this because you mentioned a
"generator that returns a deferred").

Also, there's nothing called a "coroutine" that's related to
inlineCallbacks at all, and the word is fraught with ambiguities in
Python, so it's best to just avoid it entirely.

In inlineCallbacks, nobody but the person writing the
inlineCallbacks-using function knows that there's a generator
involved. The person calling your inlineCallbacks-using function can't
see any generators; they just get a Deferred object which fires when
the generator is exhausted. The interesting part is that
inlineCallbacks is the thing responsible for iterating the generator,
not user-code. It is responsible for calling .send() on the generator
object when previously yielded deferreds have fired. The value of the
Deferred returned will be whatever is passed to returnValue in the
inlineCallbacks-using function.

-- 
Christopher Armstrong
http://radix.twistedmatrix.com/
http://planet-if.com/



More information about the Twisted-Python mailing list