blob: 46f9cddafe91855298e32db490b395e4d156fe83 [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}
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
52manager's \method{__context__} method. This is usually more convenient
53than creating another class just to serve as a context. For example:
54
55\begin{verbatim}
56from __future__ import with_statement
57from contextlib import contextmanager
58
59class Tag:
60 def __init__(self, name):
61 self.name = name
62
63 @contextmanager
64 def __context__(self):
65 print "<%s>" % self.name
66 yield self
67 print "</%s>" % self.name
68
69h1 = Tag("h1")
70
71>>> with h1 as me:
72... print "hello from", me
73<h1>
74hello from <__main__.Tag instance at 0x402ce8ec>
75</h1>
76\end{verbatim}
77\end{funcdesc}
78
79\begin{funcdesc}{nested}{ctx1\optional{, ctx2\optional{, ...}}}
80Combine multiple context managers into a single nested context manager.
81
82Code like this:
83
84\begin{verbatim}
85from contextlib import nested
86
87with nested(A, B, C) as (X, Y, Z):
88 do_something()
89\end{verbatim}
90
91is equivalent to this:
92
93\begin{verbatim}
94with A as X:
95 with B as Y:
96 with C as Z:
97 do_something()
98\end{verbatim}
99
100Note that if one of the nested contexts' \method{__exit__()} method
101raises an exception, any previous exception state will be lost; the new
102exception will be passed to the outer contexts' \method{__exit__()}
103method(s), if any. In general, \method{__exit__()} methods should avoid
104raising exceptions, and in particular they should not re-raise a
105passed-in exception.
106\end{funcdesc}
107
108\label{context-closing}
109\begin{funcdesc}{closing}{thing}
110Return a context manager that closes \var{thing} upon completion of the
111block. This is basically equivalent to:
112
113\begin{verbatim}
114from contextlib import contextmanager
115
116@contextmanager
117def closing(thing):
118 try:
119 yield thing
120 finally:
121 thing.close()
122\end{verbatim}
123
124And lets you write code like this:
125\begin{verbatim}
126from __future__ import with_statement
127from contextlib import closing
128import codecs
129
130with closing(codecs.open("foo", encoding="utf8")) as f:
131 for line in f:
132 print line.encode("latin1")
133\end{verbatim}
134
135without needing to explicitly close \code{f}. Even if an error occurs,
136\code{f.close()} will be called when the \keyword{with} block is exited.
137
138\end{funcdesc}
139
140\begin{seealso}
141 \seepep{0343}{The "with" statement}
142 {The specification, background, and examples for the
143 Python \keyword{with} statement.}
144\end{seealso}