blob: 72bf53716aa6c27c9a5bff0698526149656fc61f [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001\section{\module{contextlib} ---
2 Utilities for \keyword{with}-statement contexts.}
3
4\declaremodule{standard}{contextlib}
5\modulesynopsis{Utilities for \keyword{with}-statement contexts.}
6
7\versionadded{2.5}
8
9This module provides utilities for common tasks involving the
10\keyword{with} statement.
11
12Functions provided:
13
14\begin{funcdesc}{contextmanager}{func}
Thomas Wouters477c8d52006-05-27 19:21:47 +000015This function is a decorator that can be used to define a factory
16function for \keyword{with} statement context managers, without
17needing to create a class or separate \method{__enter__()} and
18\method{__exit__()} methods.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019
Thomas Wouters477c8d52006-05-27 19:21:47 +000020A simple example (this is not recommended as a real way of
21generating HTML!):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000022
23\begin{verbatim}
24from __future__ import with_statement
25from contextlib import contextmanager
26
27@contextmanager
28def tag(name):
29 print "<%s>" % name
30 yield
31 print "</%s>" % name
32
33>>> with tag("h1"):
34... print "foo"
35...
36<h1>
37foo
38</h1>
39\end{verbatim}
40
Thomas Wouters477c8d52006-05-27 19:21:47 +000041The function being decorated must return a generator-iterator when
42called. This iterator must yield exactly one value, which will be
43bound to the targets in the \keyword{with} statement's \keyword{as}
44clause, if any.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000045
46At the point where the generator yields, the block nested in the
47\keyword{with} statement is executed. The generator is then resumed
48after the block is exited. If an unhandled exception occurs in the
49block, it is reraised inside the generator at the point where the yield
50occurred. Thus, you can use a
51\keyword{try}...\keyword{except}...\keyword{finally} statement to trap
Thomas Wouters477c8d52006-05-27 19:21:47 +000052the error (if any), or ensure that some cleanup takes place. If an
53exception is trapped merely in order to log it or to perform some
54action (rather than to suppress it entirely), the generator must
55reraise that exception. Otherwise the generator context manager will
56indicate to the \keyword{with} statement that the exception has been
57handled, and execution will resume with the statement immediately
58following the \keyword{with} statement.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059\end{funcdesc}
60
Thomas Wouters477c8d52006-05-27 19:21:47 +000061\begin{funcdesc}{nested}{mgr1\optional{, mgr2\optional{, ...}}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062Combine multiple context managers into a single nested context manager.
63
64Code like this:
65
66\begin{verbatim}
67from contextlib import nested
68
69with nested(A, B, C) as (X, Y, Z):
70 do_something()
71\end{verbatim}
72
73is equivalent to this:
74
75\begin{verbatim}
76with A as X:
77 with B as Y:
78 with C as Z:
79 do_something()
80\end{verbatim}
81
Thomas Wouters477c8d52006-05-27 19:21:47 +000082Note that if the \method{__exit__()} method of one of the nested
83context managers indicates an exception should be suppressed, no
84exception information will be passed to any remaining outer context
85managers. Similarly, if the \method{__exit__()} method of one of the
86nested managers raises an exception, any previous exception state will
87be lost; the new exception will be passed to the
88\method{__exit__()} methods of any remaining outer context managers.
89In general, \method{__exit__()} methods should avoid raising
90exceptions, and in particular they should not re-raise a
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091passed-in exception.
92\end{funcdesc}
93
94\label{context-closing}
95\begin{funcdesc}{closing}{thing}
Thomas Wouters477c8d52006-05-27 19:21:47 +000096Return a context manager that closes \var{thing} upon completion of
97the block. This is basically equivalent to:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098
99\begin{verbatim}
100from contextlib import contextmanager
101
102@contextmanager
103def closing(thing):
104 try:
105 yield thing
106 finally:
107 thing.close()
108\end{verbatim}
109
110And lets you write code like this:
111\begin{verbatim}
112from __future__ import with_statement
113from contextlib import closing
114import codecs
115
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116with closing(urllib.urlopen('http://www.python.org')) as page:
117 for line in page:
118 print line
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000119\end{verbatim}
120
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121without needing to explicitly close \code{page}. Even if an error
122occurs, \code{page.close()} will be called when the \keyword{with}
123block is exited.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000124\end{funcdesc}
125
126\begin{seealso}
127 \seepep{0343}{The "with" statement}
128 {The specification, background, and examples for the
129 Python \keyword{with} statement.}
130\end{seealso}