Contexts and context managers

A context manager is used with the with statement. We're working with a context manager when we write something like the following:

with function(arg) as context:
    process( context )

In the preceding case, function(arg) creates the context manager.

One very commonly used context manager is a file. When we open a file, we should define a context that will also automatically close the file. Consequently, we should almost always use a file in the following way:

with open("some file") as the_file:
    process( the_file )

At the end of the with statement, we're assured that the file will be closed properly. The contextlib module provides several tools for building proper context managers. Rather than providing an abstract base class, this library offers decorators, which will transform simple functions into context managers, as well as a contextlib.ContextDecorator base class, which can be used extended to build a class that is a context manager.

We'll look at context managers in Chapter 5, Using Callables and Contexts.