On 3/24/14 6:01 PM, Chris Angelico wrote:

Easy fix. Use the "explicit capture" notation:

adders[n] = lambda a, n=n: a+n

And there you are, out of your difficulty at once!

Yes, yes, yes,  and example:

>>>> adders= list(range(4))
>>>> for n in adders:
>    adders[n] = lambda a, n=n: a+n
>
>    
>>>> adders[1](3)
>4
>>>> adders[2](3)
>5

But, and this is the big (WHY?) is that necessary? In other words, its not about experts knowing how to make this work, its about "normal" people not understanding in the first place why its a problem, and why the various solutions work to fix it; even though "we" all know that nothing is 'broken'.

And in reference to Marko's post, he's right, its not just python, but the issue is not where else is capture and scope a problem for confusion, the issue is whether python's lambda provides a significant opportunity for confusion that in the larger scheme of things (no pun intended) is not warranted.

marcus

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to