blob: 72bf53716aa6c27c9a5bff0698526149656fc61f [file] [log] [blame]
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +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
Neal Norwitzd03b0732006-03-28 05:51:02 +00007\versionadded{2.5}
8
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +00009This module provides utilities for common tasks involving the
10\keyword{with} statement.
11
12Functions provided:
13
Nick Coghlanafd5e632006-05-03 13:02:47 +000014\begin{funcdesc}{contextmanager}{func}
Nick Coghlana7e820a2006-04-25 10:56:51 +000015This function is a decorator that can be used to define a factory
Nick Coghland8accb32006-05-03 13:17:49 +000016function for \keyword{with} statement context managers, without
Nick Coghlana7e820a2006-04-25 10:56:51 +000017needing to create a class or separate \method{__enter__()} and
18\method{__exit__()} methods.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000019
Nick Coghlanafd5e632006-05-03 13:02:47 +000020A simple example (this is not recommended as a real way of
21generating HTML!):
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000022
23\begin{verbatim}
24from __future__ import with_statement
Nick Coghlanafd5e632006-05-03 13:02:47 +000025from contextlib import contextmanager
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000026
Nick Coghlanafd5e632006-05-03 13:02:47 +000027@contextmanager
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000028def 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
Nick Coghlana7e820a2006-04-25 10:56:51 +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.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +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
Nick Coghlan877cf232006-04-24 04:17:02 +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
Nick Coghland8accb32006-05-03 13:17:49 +000055reraise 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.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000059\end{funcdesc}
60
Nick Coghlanafd5e632006-05-03 13:02:47 +000061\begin{funcdesc}{nested}{mgr1\optional{, mgr2\optional{, ...}}}
Nick Coghlana7e820a2006-04-25 10:56:51 +000062Combine multiple context managers into a single nested context manager.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000063
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
Nick Coghlan877cf232006-04-24 04:17:02 +000082Note that if the \method{__exit__()} method of one of the nested
Nick Coghlanafd5e632006-05-03 13:02:47 +000083context managers indicates an exception should be suppressed, no
Nick Coghlan877cf232006-04-24 04:17:02 +000084exception information will be passed to any remaining outer context
Nick Coghland8accb32006-05-03 13:17:49 +000085managers. 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
Nick Coghlanafd5e632006-05-03 13:02:47 +000088\method{__exit__()} methods of any remaining outer context managers.
Nick Coghlan877cf232006-04-24 04:17:02 +000089In general, \method{__exit__()} methods should avoid raising
90exceptions, and in particular they should not re-raise a
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000091passed-in exception.
92\end{funcdesc}
93
94\label{context-closing}
95\begin{funcdesc}{closing}{thing}
Nick Coghlanafd5e632006-05-03 13:02:47 +000096Return a context manager that closes \var{thing} upon completion of
97the block. This is basically equivalent to:
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000098
99\begin{verbatim}
Nick Coghlanafd5e632006-05-03 13:02:47 +0000100from contextlib import contextmanager
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000101
Nick Coghlanafd5e632006-05-03 13:02:47 +0000102@contextmanager
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000103def 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}
Phillip J. Ebybdfd6932006-03-28 00:08:22 +0000112from __future__ import with_statement
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000113from contextlib import closing
Phillip J. Ebybdfd6932006-03-28 00:08:22 +0000114import codecs
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000115
Nick Coghlana7e820a2006-04-25 10:56:51 +0000116with closing(urllib.urlopen('http://www.python.org')) as page:
117 for line in page:
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +0000118 print line
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000119\end{verbatim}
120
Nick Coghlana7e820a2006-04-25 10:56:51 +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.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +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}