[Twisted-Python] Callbacks, Looping, and Variable Binding

Tommi Virtanen tv at twistedmatrix.com
Thu Jul 31 13:50:04 MDT 2003


On Thu, Jul 31, 2003 at 11:13:28AM -0600, Justin Johnson wrote:
> When I run the following code, everytime the callbacks to "onSuccess" get
> called, "item" is bound to the last element in "list".  Obviously what I
> want is to have "item" bound to the value it had when I added the
> callback.  How does one handle looping constructs like this in Twisted?

	Then don't inherit the namespace of someFunc. You could even
	move onSuccess outside of someFunc, to make sure you don't do
	that by accident.

	Besides, you are adding the outer d to deferreds once per
	iteration. That's broken.

        What do you want? I don't know what you are trying to do, so
        here's a guess, in form of a similar example as your code:

> def someFunc():
>     deferreds = []
> 
>     def onSuccess(results):
>        d = item.doSomethingElseThatReturnsDeferred()
>        return d
> 
>     d = doSomethingThatReturnsDeferred()
> 
>     for item in list:
>         d.addCallbacks(onSuccess, log.err)
>         deferreds.append(d)
> 
>     return defer.DefferedList(deferreds)

def onSuccess(item):
    d = item.doSomethingElseThatReturnsDeferred()
    return d

def someFunc(listOfItems):
    deferreds = []

    for item in listOfItems:
        d = doSomethingThatReturnsDeferred(item)
        d.addCallbacks(onSuccess, log.err)
        deferreds.append(d)

    return defer.DeferredList(deferreds)

-- 
:(){ :|:&};:




More information about the Twisted-Python mailing list