Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables declared inside a WITH block outside of it - why does it work? [duplicate]

I'm starting to learn some Python and found out about the with block.

To start of here's my code:

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    with open(WORDLIST_FILENAME, 'r') as inFile:
        line = inFile.readline()
        wlist = line.split()
        print("  ", len(wlist), "words loaded.")
    print(wlist[0])
    inFile.close()
    return wlist

My understanding was that the inFile variable would only exist/be valid inside the block. But the inFile.close() call after the block does not crash the program or throw an exception?

Similarly wlist is declared inside the block, yet I have no issue with returning wlist at the end of the method.

Can anyone help explain why it works like this? Perhaps my understanding of with blocks is incorrect.

like image 856
user1021085 Avatar asked Nov 07 '25 22:11

user1021085


1 Answers

You can read the variables inside a with block because the with statement does't add any scope to your program, it's just a statement to make your code cleaner when calling the object you refer in it.

This:

with open('file.txt', 'r') as file:
    f = file.read()
print(f)

Outputs the same as:

file = open('file.txt', 'r') 
f = file.read()
file.close()

print(f)

So the main difference is that makes your code cleaner

like image 78
Stack Avatar answered Nov 10 '25 13:11

Stack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!