Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Python 2.6 and 3.0 introduced a new exception-related statement—the with, and its optional as clause. This statement is designed to
work with context manager objects, which support a new method-based
protocol. This feature is also available as an option in 2.5, enabled
with an import of this form:
from __future__ import with_statement
In short, the with/as statement is designed to be an
alternative to a common try/finally usage idiom; like that statement, it
is intended for specifying termination-time or “cleanup” activities
that must run regardless of whether an exception occurs in a
processing step. Unlike try/finally, though, the with statement supports a richer object-based protocol for specifying
both entry and exit actions around a block of code.