[Twisted-Python] Mixing generator style (yield+twisted.flow) functions with deferreds?

Jean-Paul Calderone exarkun at divmod.com
Tue Mar 21 07:49:17 MST 2006


On Tue, 21 Mar 2006 14:36:45 +0100, Marcin Kasperski <marcin.kasperski at softax.com.pl> wrote:
>I develop some twisted application using 'traditional' method
>(plenty of deferreds and small callbacks). Works well, but is
>not too readable and a bit difficult to maintain. Therefore, I
>would like to move into twisted.flow-style coding (single longer
>function returning flow.Cooperate() from time to time, wrapped
>with flow.Deferred).
>
>There is a problem nevertheless. I still have some functions
>which return deferreds and which results are needed in the
>processing. Is it possible to somehow wrap them and keep
>yield-style of coding?

There's no need to use twisted.flow for this, and I would discourage you from doing so.  Instead, if you want to use this style of programming, simply use waitForDeferred and deferredGenerator from twisted.internet.defer.

> [snip]
>
>What is the problem? Imagine that somewhere within the function I
>need to call some deferred-returning function (and use its
>result in the further computation)? For instance so:
>
>  def someFunctionBody(name):
>     x = 1
>     print name, x
>     yield flow.Cooperate()
>     x = x+1
>     print name, x
>     yield flow.Cooperate()
>     d = functionReturningDeferredWhichFiresInteger(x)
>     #### and here some magic to extract value from d to x
>     #### would be so nice
>     print name, x
>     yield flow.Cooperate()
>     x = x+1
>     print name, x
>     yield x


    def someFunction(name):
        x = 1
        print name, x
        yield None
        x += 1
        print name, x
        yield None
        d = defer.waitForDeferred(funcReturnDef(x))
        yield d
        x = d.getResult()
        print name, x
        ...
    someFunction = defer.deferredGenerator(someFunction)

Jean-Paul




More information about the Twisted-Python mailing list