2 ms·
> That's again a decision made by Python. Some other languages behave as if each iteration had declared a different variable. Doing that requires block scoping
by masklinn 3y ago
> That's again a decision made by Python. Some other languages behave as if each iteration had declared a different variable.
Doing that requires block scoping. Python does not have block scoping. The alternative would be to create a dedicated pseudo-scoping for for loops, which is technically possible (e.g. `except` blocks have special casing to avoid circular references) but is a lot of additional complexity, not “just” changing the scoping of iteration variables.
Furthermore (1) happens to provide a pretty good workaround: you can set the iteration variable as a default value of the closure, it’ll be evaluated at the creation of the closure thus “fixing” it.