9 ms·
> Second is just how things work, the function is a closure that evaluates the non local variable when you run it. In python, yes. In other languages, not nece
by gpm 3y ago
> Second is just how things work, the function is a closure that evaluates the non local variable when you run it.
In python, yes. In other languages, not necessarily. There are two ways that this could reasonably not be the result:
1. For i in iterator could create a new variable i (shadowing the old i) on each iteration of the loop. This isn't how python works (which also means you can do things like access i after a for loop terminates) but there are languages that work that way.
2. Capturing an integer could copy that integer, instead of copying a pointer to a value that can change in the future. Again, not how python works, but how some languages work.
The first in particular I think is more intuitive in other languages, and leads to other footguns in python as well, e.g.:
for i in range(5):
for i in range(10):
pass
print("Finished loop iteration", i) # I meant 0, 1, 2, 3, 4. Instead I got 9 9 9 9 9