Using a Context

There are a few Python library classes which provide context information that is used by the with statement. The most commonly-used class is the file class.

There are two forms of the with statement. In the first, the context object does not provide a context-specific object to work with. In the second, the context provides us an object to be used within the context.

with context : suite

with context as variable : suite

We'll look at the second form, since that is how the file class works. A file object is a kind of context manager, and responds to the protocol defined by the with statement.

When we open a file for processing, we are creating a context. When we leave that context, we want to be sure that the file is properly closed. Here's the standard example of how this is used.

with file('someData.txt','r') as theFile:
   for aLine in theFile:
       print aLine
# the file was closed by the context manager
1

We create the file, which can be used as a context manager. The with statement enters the context, which returns a file object that we can use for input and output purposes. The as clause specifies that the working object is assigned to theFile.

2

This is a pretty typical for statement that reads each line of a file.

3

The with statement also exits the context, irrespective of the presence or absence of exceptions. In the case of a file context manager, this will close the file.

In the previous example, we saw that the file factory function is used to create a context manager. This is possible because a file has several interfaces: it is a context manager as well as being a working file object. This is potentially confusing because it conflate file context manager with the working file object. However, it also

Thas the advantage of making the with statement optional. In many applications, improperly closed files have few real consequences, and the carefully managed context of a with statement isn't necessary.