On Mon, 24 Mar 2014 18:44:37 -0500, Mark H Harris wrote: > 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'.
The reason this is surprising is that people want their functions to magically read their mind and do what they want, even when they want it to do something different each time. If you have early binding, then people who want late binding will complain that it does the wrong thing. If you have late binding, then people who want early binding will complain that it does the wrong thing. Even when they are the same people. And *none of this has anything to do with lambda*. Functions created with def exhibit the exact same behaviour. -- Steven -- https://mail.python.org/mailman/listinfo/python-list