Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make variable visibility in block statement in Python?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading