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