Using WITH

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 = # do something

# old method
myfile2 = open('filename.ext')
data2 = # do something

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

One comment

  1. Hi! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading your articles.
    Can you suggest any other blogs/websites/forums that go over the same topics?

    Thanks for your time!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.