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.
To access a function variable outside the function without using "global" with Python, we can add an attribute to the function. to add the bye attribute to the hi function. We can do this since functions are objects in Python. And then we get the value with hi.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.
you have to declare the variable outside the function to use it. variables declared inside a function can only be accessed inside that function.
Yes, the context manager will be available outside the with statement and that is not implementation or version dependent. with statements do not create a new execution scope.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With