[Twisted-Python] Fwd: Adding callbacks using loop variables

Saoili saoili at gmail.com
Wed May 6 02:26:25 MDT 2015


Hi folks,

I was going to ask a question, but a colleague resolved it for me. I
thought I'd share the result!

We often end up using lambda to add callbacks, especially where we want to
pass the response to a deferred into a function and it's not the first
parameter. However, if you do that inside a loop and one of the variables
you're passing is a loop variable, you're going to get the same value for
that loop variable in all of your callbacks (the last one). The solution is
to avoid calling lambda, either by reordering the expected params in
function you're calling, or by creating a small function that just reorders
what's passed to it and sends them to that function in the right order.

Hopefully that's useful to someone.
Sorcha


Eg. code BEFORE
            for loop_var in a_dict['loop_vars']:
                d = self.returns_a_deferred(loop_var["x"])
                d.addCallback(
                    lambda ret_val: self.do_another_thing(
                        other_param, loop_var.copy(), ret_val
                    )
                )
                _dlist.append(d)
            return defer.DeferredList(_dlist)

Eg. code AFTER
            def other_func(ret_val, other_param, loop_var):
                return self.do_other_thing(
                    other_param, loop_var, ret_val
                )

            for loop_var in a_dict['loop_vars']:
                d = self.returns_a_deferred(loop_var["x"])
                d.addCallback(other_func, other_param, loop_var)
                _dlist.append(d)
            return defer.DeferredList(_dlist)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-python/attachments/20150506/9c3bbf3b/attachment.html>


More information about the Twisted-Python mailing list