This isn’t brand-spanking new (it’s been in trunk for quite a while already), but Bob Ippolito made an update to it recently, so it caught my eye. I think this is such a cool, and incredibly useful, part of Twisted, that it’s worth mentioning just for anybody who hasn’t seen it yet.
from twisted.internet import reactor
from twisted.internet import defer
waitFor = defer.waitForDeferred
def getSomeDeferred():
d = defer.Deferred()
reactor.callLater(
2, d.callback, 'This is a string that yells "foo!"')
return d
def anotherDeferred(needle, haystack):
d = defer.Deferred()
reactor.callLater(
2, d.callback, haystack.find(needle))
return d
@defer.deferredGenerator
def find(needle):
d = waitFor(getSomeDeferred())
yield d
haystack = d.getResult()
print 'I got my first deferred result'
d = waitFor(anotherDeferred(needle, haystack))
yield d
print 'I found', repr(needle), 'at character', d.getResult()
return
find('foo!')
reactor.run()
So now you can write deferred procedures that look synchronous. None of this “writing many small statements, nested, backwards” nonsense. That’s awesome.
Updated: I noticed that the code I wrote didn’t really demonstrate the power of deferredGenerator, so I’ve updated the code. I still think this is really cool.
![[ Hacker ]](/static/images/hacker.png)