Is it legal to access the variable, ktext
, which is defined in a with-as
block, out of the block as the code below?
The code is as below.
try:
with open("pub", "r") as f:
ktext = f.read().strip()
except:
ktext = ""
print(ktext)
Is it legal to access the variable, ktext
, which is defined in a with-as
block, out of the block as the code below?
The code is as below.
try:
with open("pub", "r") as f:
ktext = f.read().strip()
except:
ktext = ""
print(ktext)
Yes, in Python, variable scope extends outside of blocks (with the exception of function and class blocks). This means you can do stuff like:
if True:
a = 1
a += 1
print(a) # 2
The same principle applies for with
blocks:
with open('data.txt') as file:
data = file.read()
print(data)
Note that if an exception is raised, the variable isn't assigned (but in your case, you already handle this with ktext = ""
in the except-block).
The 'with' statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed and the scope of variable defined within with block extends outside with block.
with expression [as variable]:
with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has enter() and exit() methods. After execution of the with-block is finished, the object's exit() method is called, even if the block raised an exception, and can therefore run clean-up code.
Here It would be more clean to initialize the variables before with block as variable instance might not at all get created if the with-block throws execption before variable instantiation, like
ktext = ""
with open("k_pub", "r") as f:
ktext = f.read().strip()
print(ktext)