Is it good practice to depend on python's with...as statement

Blaine picture Blaine · Feb 8, 2013 · Viewed 11k times · Source

I'm curious if it is considered safe or good practice to depend on python's with...as statement. For example when opening a file:

with open("myfile","w") as myFile:
    #do something

So in this example I neglected to explicitly call myFile.close() however I can assume it was called when python exited the with...as statement by calling the objects __exit__() method. Is it good practice/safe to depend upon this or would it be better to always explicitly call file.close()

Answer

Martijn Pieters picture Martijn Pieters · Feb 8, 2013

This is what context managers are for, to rely on them to close the file for you. Context managers are called even if there was an exception.

The alternative is to use an finally block instead:

myFile = open("myfile","w")
try:
    # do something with myFile
finally:
    myFile.close()

but because the block inside of the try: might be long, by the time you get to the finally statement you have forgotten what you were setting this up for.

Context managers are more powerful still. Because the __exit__ method is informed of any exceptions, they can act as exception handlers as well (ignore the exception, raise another, etc.).