[Twisted-Python] Returning a DeferredList?

Nathan nathan.stocks at gmail.com
Mon Jun 30 17:52:58 EDT 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
      return False

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

def main_func():
   if check_db():   # This eventually returns True or False
      # Do some stuff
      # 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])
   return dl             # The crucial line!

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

reactor.callLater(2.0, reactor.stop)

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