[Twisted-Python] Returning a DeferredList?

Terry Jones terry at jon.es
Mon Jun 30 19:05:02 EDT 2008


>>>>> "Nathan" == Nathan  <nathan.stocks at gmail.com> writes:

Nathan> On Mon, Jun 30, 2008 at 4:20 PM, Terry Jones <terry at jon.es> wrote:
>> You're not using deferreds properly. In the simple/typical case, when you
>> call a function that returns a deferred, you will want to add (at least) a

Nathan> I don't think that's true.  Jean-Paul was the one who told me to do
Nathan> it that way in the first place:

Nathan> http://twistedmatrix.com/pipermail/twisted-python/2008-April/017304.html

Sorry, but that doesn't seem related - you may have misinterpreted what
Jean-Paul was saying.

Nathan> If your theory was true, I would be getting garbage everywhere I
Nathan> return (and use) complicated objects, and I'd be getting True
Nathan> everywhere that I return booleans.

I don't fully understand this last sentence. Try this:

    from twisted.internet import defer
    d = defer.Deferred()

    if d: print 'hey hey hey'

Python treats the deferred as true here. Exactly the same goes for your
original code:

    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

The return result of check_db is a deferred. If you test it with an 'if'
it's always going to be true.  If you do this

    def main_func():
       d = check_db()
       print d
       if d:
          # Do some stuff
       else:
          # Do some different stuff


You'll see that d is a deferred.

In both code examples you sent (the pseudo and the working) you are not
treating the return value of a function that returns a deferred as a
deferred. In one example you're testing it in an 'if' and in the other
you're printing it. You need to add a callback in both cases.

Terry




More information about the Twisted-Python mailing list