2

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)
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
codexplorer
  • 541
  • 5
  • 21
  • 1
    Related question regarding `if`-blocks: [What's the scope of a variable initialized in an if statement?](https://stackoverflow.com/questions/2829528/whats-the-scope-of-a-variable-initialized-in-an-if-statement) – TrebledJ Apr 17 '19 at 09:52

2 Answers2

3

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).

TrebledJ
  • 8,713
  • 7
  • 26
  • 48
2

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)
Kaushal Pahwani
  • 464
  • 3
  • 11