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

Tristan Seligmann mithrandi at mithrandi.net
Wed May 6 04:15:44 MDT 2015


On 6 May 2015 at 10:26, Saoili <saoili at gmail.com> wrote:
> 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)

There's another common trick for dealing with this, that relies on the
fact that default argument values are evaluated when the lambda
expression itself (not the body of the lambda!) is initially
evaluated; basically, just add an extra parameter with a default value
of the loop variable. For example:

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

However, separating the code out into a separate function may serve to
make the code clearer.
-- 
mithrandi, i Ainil en-Balandor, a faer Ambar




More information about the Twisted-Python mailing list