<div dir="ltr"><br><div class="gmail_quote"><div dir="ltr"><div><div><div><div><div><div><div>Hi folks,<br><br></div>I was going to ask a question, but a colleague resolved it for me. I thought I'd share the result!<br><br></div><div>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.<br></div><br></div><div>Hopefully that's useful to someone.<br></div><div></div>Sorcha<br><br><br></div>Eg. code BEFORE            <br>            for loop_var in a_dict['loop_vars']:<br>                d = self.returns_a_deferred(loop_var["x"])<br>                d.addCallback(<br>                    lambda ret_val: self.do_another_thing(<br>                        other_param, loop_var.copy(), ret_val<br>                    )<br>                )<br>                _dlist.append(d)<br>            return defer.DeferredList(_dlist)<br><br>Eg. code AFTER<br></div>            def other_func(ret_val, other_param, loop_var):<br></div>                return self.do_other_thing(<br></div>                    other_param, loop_var, ret_val<br><div><div>                )<br><div><div>            <br>            for loop_var in a_dict['loop_vars']:<br>                d = self.returns_a_deferred(loop_var["x"])<br>                d.addCallback(other_func, other_param, loop_var)<br>                _dlist.append(d)<br>            return defer.DeferredList(_dlist)<br></div></div></div></div></div>
</div><br></div>