twisted.internet.defer.deferredGenerator(f) function documentationtwisted.internet.defer
View Source
deferredGenerator and waitForDeferred help you write Deferred-using code that looks like a regular sequential function. Consider the use of inlineCallbacks instead, which can accomplish the same thing in a more concise manner.
There are two important functions involved: waitForDeferred, and deferredGenerator. They are used together, like this:
@deferredGenerator
def thingummy():
thing = waitForDeferred(makeSomeRequestResultingInDeferred())
yield thing
thing = thing.getResult()
print(thing) #the result! hoorj!
waitForDeferred returns something that you should immediately yield; when your generator is resumed, calling thing.getResult() will either give you the result of the Deferred if it was a success, or raise an exception if it was a failure. Calling getResult is absolutely mandatory. If you do not call it, your program will not work.
deferredGenerator takes one of these waitForDeferred-using generator functions and converts it into a function that returns a Deferred. The result of the Deferred will be the last value that your generator yielded unless the last value is a waitForDeferred instance, in which case the result will be None. If the function raises an unhandled exception, the Deferred will errback instead. Remember that return result won't work; use yield result; return in place of that.
Note that not yielding anything from your generator will make the Deferred result in None. Yielding a Deferred from your generator is also an error condition; always yield waitForDeferred(d) instead.
The Deferred returned from your deferred generator may also errback if your generator raised an exception. For example:
@deferredGenerator
def thingummy():
thing = waitForDeferred(makeSomeRequestResultingInDeferred())
yield thing
thing = thing.getResult()
if thing == 'I love Twisted':
# will become the result of the Deferred
yield 'TWISTED IS GREAT!'
return
else:
# will trigger an errback
raise Exception('DESTROY ALL LIFE')
Put succinctly, these functions connect deferred-using code with this 'fake blocking' style in both directions: waitForDeferred converts from a Deferred to the 'blocking' style, and deferredGenerator converts from the 'blocking' style to a Deferred.
| Function | unwindGenerator | Undocumented |