Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This situation is mentioned in the docs:

https://docs.python.org/3.8/faq/programming.html#why-do-lamb...

"This happens because i is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of i is 4, so all the functions now return 42, i.e. 16."

These sort of scoping gotchas are pretty common across all programming languages and are a great argument for unit testing. As usual the answer is be more explicit what you're asking the language to do:

>>> powers_of_x = [lambda x, i=i: x*i for i in range(10)]

>>> [f(2) for f in powers_of_x]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Note the positional argument with default "i=i."

More discussion:

https://stackoverflow.com/questions/452610/how-do-i-create-a...



Any feature that is a "great argument for unit testing" is a poor feature.


Isn't there something wrong if you have to explicitly state i=i?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: