[Twisted-Python] Returning a DeferredList?

Nathan nathan.stocks at gmail.com
Mon Jun 30 15:52:58 MDT 2008


I regularly use the return values of deferreds to simulate synchronous
behaviour like this:

def handle_db_result(result):
   if ({some logic stuff}):
      return True
   else:
      return False

def check_db():
   d = {some db query that returns a deferred}
   d.addCallback(handle_db_result)
   return d

def main_func():
   if check_db():   # This eventually returns True or False
      # Do some stuff
   else:
      # Do some different stuff


So now I'm trying to do the same thing with DeferredList's, but
apparently the semantics aren't the same.  Here's some actual runnable
sample code trying to use the DeferredList:

from twisted.internet import reactor, defer

def callback_function(results):
   return "(--> This is the value that I want to get into retval! <--)"

def make_a_list():
   deferred1 = defer.Deferred()
   deferred2 = defer.Deferred()
   dl = defer.DeferredList([deferred1, deferred2])
   dl.addCallback(callback_function)
   deferred1.callback('one')
   deferred2.callback('two')
   return dl             # The crucial line!

def test():
   retval = make_a_list()
   print "retval is:", retval

reactor.callWhenRunning(test)
reactor.callLater(2.0, reactor.stop)
reactor.run()



The actual output of the above script is:

retval is: <DeferredList at 0x7a30a8  current result: '(--> This is
the value that I want to get into retval! <--)'>

Through some trial and error I found that if I change that "crucial
line" above to "return dl.result", then it appears to work how I like.
 Is that what I should be doing, or did I just get lucky in that
particular instance??

Also, I notice that if one of the deferred's errbacked, then the
DeferredList seems to errback as well.  It shouldn't do that according
to http://twistedmatrix.com/projects/core/documentation/howto/defer.html#auto7
... so I filed a bug (#3323).

~ Nathan




More information about the Twisted-Python mailing list