twisted.internet.defer.inlineCallbacks(f)
function documentationtwisted.internet.defer
View Source
inlineCallbacks
helps you write Deferred
-using code that looks like a regular sequential function. For example:
@inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() print(thing) # the result! hoorj!
When you call anything that results in a Deferred
, you can simply yield it; your generator will automatically be resumed when the Deferred's result is available. The generator will be sent the result of the Deferred
with the 'send' method on generators, or if the result was a failure, 'throw'.
Things that are not Deferred
s may also be yielded, and your generator will be resumed with the same object sent back. This means yield
performs an operation roughly equivalent to maybeDeferred
.
Your inlineCallbacks-enabled generator will return a Deferred
object, which will result in the return value of the generator (or will fail with a failure object if your generator raises an unhandled exception). Note that you can't use return result
to return a value; use returnValue(result)
instead. Falling off the end of the generator, or simply using return
will cause the Deferred
to have a result of None
.
Be aware that returnValue
will not accept a Deferred
as a parameter. If you believe the thing you'd like to return could be a Deferred
, do this:
result = yield result returnValue(result)
The Deferred
returned from your deferred generator may errback if your generator raised an exception:
@inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() if thing == 'I love Twisted': # will become the result of the Deferred returnValue('TWISTED IS GREAT!') else: # will trigger an errback raise Exception('DESTROY ALL LIFE')
It is possible to use the return
statement instead of returnValue
:
@inlineCallbacks def loadData(url): response = yield makeRequest(url) return json.loads(response)
You can cancel the Deferred
returned from your inlineCallbacks
generator before it is fired by your generator completing (either by reaching its end, a return
statement, or by calling returnValue
). A CancelledError
will be raised from the yield
ed Deferred
that has been cancelled if that Deferred
does not otherwise suppress it.
Function | unwindGenerator | Undocumented |