3

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.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
user1021085
  • 729
  • 3
  • 10
  • 28
  • See https://stackoverflow.com/questions/45100271/scope-of-variable-within-with-statement?rq=1 `with` does not create a scope – Ipiano Aug 26 '19 at 17:22
  • On repeatedly calling `.close()`, see [here](https://stackoverflow.com/questions/42954401/python-file-object-allows-you-to-close-a-file-that-is-already-closed). The `with` statement only specifies that clean-up should be performed on the object in the statement (like a file object). – FObersteiner Aug 26 '19 at 17:38

1 Answers1

3

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

Stack
  • 1,028
  • 2
  • 10
  • 31