On Fri, Aug 19, 2016 at 3:00 AM, Terry Reedy <tjre...@udel.edu> wrote: > On 8/18/2016 5:32 AM, Steven D'Aprano wrote: > >>> Beginners often do not understand that the body of a lambda expression >>> is evaluated in a new local namespace, and only when the resulting >>> function is called, the same as with a def statement. They then neglect >>> to capture current values when writing lambda expressions in a for loop. >> >> >> Sure. But since the behaviour of def functions and lambda functions are >> identical, writing a named def won't solve that problem. > > > It will if people do not make the same mental mistake when writing a def, > because they think def functions and 'lambdas' behave differently. > > I can't remember every seeing "my def function in a loop does not work > right" while "my lambda in a loop does not work right" is distressingly > common. What I don't know is whether the sparsity of the former type of > report is because those subject to the error get it right when they use def > in a loop or because they never use def in a loop.
The latter. People who are confused about lambda in a loop are not magically unconfused by def in a loop; in fact, I'd expect to see *more* confusion, because those same people are likely to be confused by the fact that a "declaration" can be done more than once and have different effects. That is to say, a lambda function looks like it's being created at the point where you use it, but a def function looks like a declaration, which is independent of loops and stuff. I don't have actual stats on how many people are confused by each, but I know both points do cause confusion. Having def statements inside loops is definitely [1] rarer than using lambda expressions inside loops. ChrisA [1] Pun intended. And I'm not sorry. -- https://mail.python.org/mailman/listinfo/python-list