[Twisted-Python] Calling deferred within a callback, good or bad idea ?

Thomas Hervé therve at free.fr
Fri May 19 12:26:03 MDT 2006


Selon Stéphane Brault <stephane_brault at yahoo.fr>:

> Hi,
>  I have to call a web service then process the answer, according to the
> answer I may have to call the service again.
>  The traditional way to go would be :
>  condition = 1
>  while condition:
>      message = callWebService()
>      condition = processMessage(message)
>
>  Here is what I do :
>  def function():
>
>      def myCalback(message):
>          condition = processMessage(message)
>          if condition:
>              deferred = callWebService()
>               deferred.addCallback(myCallback)
>
>      deferred = callWebService()
>      deferred.addCallback(myCallback)
>
>  I was wondering if it was the way to go or if there was a better way, since
> I'm not quite sure about the impact of calling new deffered within a
> callback.

You may have a recursion problem with this kind of code (I'm not quite sure when
it happens but it does). One good way is to use deferredGenerator:

# Not tested
def function():
    condition = True
    while condition:
        wfd =  defer.waitForDeferred(callWebService())
        yield wfd
        condition = wfd.getResult()
function = defer.deferredGenerator(function)

--
Thomas




More information about the Twisted-Python mailing list