It is not obvious what benefit the with statement brings. For example the preferred way of opening a file is by using the with statement rather than than an assignment as shown below.
# preferred method with open('filename.ext') as myfile1: data1 = myfile1.read() # do something # old method myfile2 = open('filename.ext') data2 = myfile2.read() # do something myfile2.close()
In other languages with is little more than a shortcut to save typing in fully qualified names but that is not happening here. So why is this preferred? Those paying attention will have noticed I did not close myfile1. This is not a typo.
The reason for using the with command is it ensures that a cleanup of the variable is done once it is finished with. If in the old method the read caused an exception myfile2 would have been left open. Using with, the cleanup is done automatically whether the end of the block is reached or an exception occurs. For the open class, cleanup is naturally to close the file.
You can of course achieve the same result using try at the expense of several ugly lines which does nothing for readability. For those looking for a more technical explanation and how to make a class that can be used with the with statement have a look at Fredrik Lundh’s post here.
One final note is for Python 2.5 users who will not be able to run the code fragment above as it stands. Although the with statement was added in 2.5 it resides in __future__ module and needs to be imported. To support Python 2.5 add the following to the top of your code.
from __future__ import with_statement