Next / Previous / Contents / TCC Help System / NM Tech homepage

23.9. The with statement and context managers

The purpose of this statement is to protect a block of code with a context manager that insures that certain initialization and cleanup steps get performed, regardless of whether that block raises an exception.

A context manager is a class that has .__enter__() and .__exit__() methods.

  1. The .__enter__() method performs any necessary initialization, and returns a value.

  2. The .__exit__() method is always executed to perform necessary cleanup actions.

Starting with version 2.6, Python now was a with statement that executes a block using a context manager. Here is the general form, where B is the block to be executed.

with E[ as V]:

Python's file class is a context manager; its .__enter__() method returns the opened file, and its .__exit__() method closes the file. For example, suppose you want to call a function beat() and pass it an opened file named "goat", but you want to be sure the file is closed even if the beat() function raises an exception. This code would do that:

with open("goat") as inFile:

When the beat() function terminates (either normally or because it raised an exception), the file will be closed (in the file.__exit__() method). If the function raised an exception, that exception will then be re-raised.

Starting in Python 2.7, you can enclose a block in multiple context managers by repeating the “E[ as V” parts of the statement. For example:

with open('in') as inFile, open('out', 'w') as outFile:
    for rawLine in inFile: