how to make variable visibility in block statement in Python?

Question:

How to achieve an effect like :

#there is no variable named `i`
for i in range(1):
    pass
print(i) #why 

I don’t want to make i visitable after the for statement finished.

But I don’t want to use del i manually.

Asked By: Z.Lun

||

Answers:

This is just part of Python’s design. A for loop assigns to i on each iteration, just as if it did i = next(some_iterator). Just like any other assignment, the i variable persists until it gets rebound to something else, or until you remove it with del i.

Variables in Python are not (usually) limited to a single block, only functions (and a few other language constructs built out of them, like comprehensions and generator expressions) have their own scopes in that way. This is different than other programming languages that have a more expansive form of lexical scoping, where each block can have its own scope. (The one exception is exception handling code, except SomeExeptionType as e, where the e variable gets deleted after the end of the block, to help avoid reference loops between exception tracebacks and stack frames.)

If you want to be sure you don’t leak any variables, put all your code into separate functions. Local variables will never leak outside of their function.

def do_a_loop():
    for i in range(1):
        pass
    # i is still defined here, but only until the end of the function body

do_a_loop()
print(i)     # this will raise, as i is not defined as a global variable
Answered By: Blckknght
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.