In Python today, for loops run in the same scope as their enclosing block. Some languages have for loops create their own scope, as functions and classes do.
Python’s current behaviour is discussed here.
Some people would like Python for each iteration of a loop to run in its own scope.
That would probably solve the issue described in the topic “Make lambdas proper closures” but there may be performance or other costs.
There is a FAQ about the behaviour of lambdas in loops.
Changing the behaviour of loops would break backwards compatibility and break any code that expects variables inside a for loop to be the visible outside of the loop, and so would need to initially be a __future__
import.
Given all that, what do you think future Python versions (probably no earlier than 3.12) should do with for loops?
- No change, leave loops as they are.
- Change loops to use their own scope.
- No change for loops by default, but add an option to run them in a new scope.
0 voters
(This is an unofficial and non-binding poll. There may be technical reasons why any change to for loop scopes is impossible or too difficult.)