Should loops be in their own scope? [poll]

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.)

The current status is non-obvious enough to require checking what the scoping rules are every once in a while.

This would be a major change, requiring a 4.0 release.

Think about all the code that defines names for later use within a with statement.