Octaviour
Octaviour

Reputation: 805

using python variable outside with statement

In a Python script, I encountered a variable that was defined inside a with statement, but that was used outside the statement, like file in the following example:

with open(fname, 'r') as file:
    pass
print(file.mode)

Intuitively I would say that file should not exist outside the with statement and that this only works by accident. I could not find a conclusive statement in the Python documentation on whether this should work or not though. Is this type of statement safe for use (also for future python versions), or should it be avoided? A pointer to this information in the Python docs would be very helpful as well.

Upvotes: 28

Views: 9594

Answers (1)

Billy
Billy

Reputation: 5609

Variable scope only applies at the function, module, and class levels. If you are in the same function/module/class, all variables defined will be available within that function/module/class, regardless of whether it was defined within a with, for, if, etc. block.

For example, this:

for x in range(1):
    y = 1
print(y)

is just as valid (although pointless) as your example using the with statement.

However, you must be careful since the variable defined within your code block might not actually be defined if the block is never entered, as in this case:

try:
    with open('filedoesnotexist', 'r') as file:
        pass
except:
    pass # just to emphasize point

print(file.mode)

Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    file.mode
NameError: name 'file' is not defined

Good description of LEGB rule of thumb for variable scope

Upvotes: 25

Related Questions