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.