blob: 0c02cd1b44ce0887e30bb12d0779074c5ce3a458 [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
14\begin{funcdesc}{contextmanager}{func}
15This function is a decorator that can be used to define context managers
16for use with the \keyword{with} statement, without needing to create a
17class or separate \method{__enter__()} and \method{__exit__()} methods.
18
19A simple example:
20
21\begin{verbatim}
22from __future__ import with_statement
23from contextlib import contextmanager
24
25@contextmanager
26def tag(name):
27 print "<%s>" % name
28 yield
29 print "</%s>" % name
30
31>>> with tag("h1"):
32... print "foo"
33...
34<h1>
35foo
36</h1>
37\end{verbatim}
38
39When called, the decorated function must return a generator-iterator.
40This iterator must yield exactly one value, which will be bound to the
41targets in the \keyword{with} statement's \keyword{as} clause, if any.
42
43At the point where the generator yields, the block nested in the
44\keyword{with} statement is executed. The generator is then resumed
45after the block is exited. If an unhandled exception occurs in the
46block, it is reraised inside the generator at the point where the yield
47occurred. Thus, you can use a
48\keyword{try}...\keyword{except}...\keyword{finally} statement to trap
49the error (if any), or ensure that some cleanup takes place.
50
51Note that you can use \code{@contextmanager} to define a context
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +000052object's \method{__context__} method. This is usually more convenient
53than creating another class just to serve as a context manager.
54For example:
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000055
56\begin{verbatim}
57from __future__ import with_statement
58from contextlib import contextmanager
59
60class Tag:
61 def __init__(self, name):
62 self.name = name
63
64 @contextmanager
65 def __context__(self):
66 print "<%s>" % self.name
67 yield self
68 print "</%s>" % self.name
69
70h1 = Tag("h1")
71
72>>> with h1 as me:
73... print "hello from", me
74<h1>
75hello from <__main__.Tag instance at 0x402ce8ec>
76</h1>
77\end{verbatim}
78\end{funcdesc}
79
80\begin{funcdesc}{nested}{ctx1\optional{, ctx2\optional{, ...}}}
81Combine multiple context managers into a single nested context manager.
82
83Code like this:
84
85\begin{verbatim}
86from contextlib import nested
87
88with nested(A, B, C) as (X, Y, Z):
89 do_something()
90\end{verbatim}
91
92is equivalent to this:
93
94\begin{verbatim}
95with A as X:
96 with B as Y:
97 with C as Z:
98 do_something()
99\end{verbatim}
100
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +0000101Note that if the \method{__exit__()} method of one of the nested context managers
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000102raises an exception, any previous exception state will be lost; the new
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +0000103exception will be passed to the \method{__exit__()} methods of any remaining
104outer context managers. In general, \method{__exit__()} methods should avoid
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000105raising exceptions, and in particular they should not re-raise a
106passed-in exception.
107\end{funcdesc}
108
109\label{context-closing}
110\begin{funcdesc}{closing}{thing}
111Return a context manager that closes \var{thing} upon completion of the
112block. This is basically equivalent to:
113
114\begin{verbatim}
115from contextlib import contextmanager
116
117@contextmanager
118def closing(thing):
119 try:
120 yield thing
121 finally:
122 thing.close()
123\end{verbatim}
124
125And lets you write code like this:
126\begin{verbatim}
Phillip J. Ebybdfd6932006-03-28 00:08:22 +0000127from __future__ import with_statement
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000128from contextlib import closing
Phillip J. Ebybdfd6932006-03-28 00:08:22 +0000129import codecs
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000130
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +0000131with closing(urllib.urlopen('http://www.python.org')) as f:
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000132 for line in f:
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +0000133 print line
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000134\end{verbatim}
135
136without needing to explicitly close \code{f}. Even if an error occurs,
137\code{f.close()} will be called when the \keyword{with} block is exited.
138
139\end{funcdesc}
140
141\begin{seealso}
142 \seepep{0343}{The "with" statement}
143 {The specification, background, and examples for the
144 Python \keyword{with} statement.}
145\end{seealso}