blob: 6c80a7162315606bc12fa70f593b774c2127e1c9 [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 Coghlane708cf52006-04-25 11:05:56 +000014\begin{funcdesc}{context}{func}
Nick Coghlana7e820a2006-04-25 10:56:51 +000015This function is a decorator that can be used to define a factory
16function for \keyword{with} statement context objects, without
17needing to create a class or separate \method{__enter__()} and
18\method{__exit__()} methods.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000019
20A simple example:
21
22\begin{verbatim}
23from __future__ import with_statement
Nick Coghlana7e820a2006-04-25 10:56:51 +000024from contextlib import contextfactory
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000025
Nick Coghlana7e820a2006-04-25 10:56:51 +000026@contextfactory
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000027def tag(name):
28 print "<%s>" % name
29 yield
30 print "</%s>" % name
31
32>>> with tag("h1"):
33... print "foo"
34...
35<h1>
36foo
37</h1>
38\end{verbatim}
39
Nick Coghlana7e820a2006-04-25 10:56:51 +000040The function being decorated must return a generator-iterator when
41called. This iterator must yield exactly one value, which will be
42bound to the targets in the \keyword{with} statement's \keyword{as}
43clause, if any.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000044
45At the point where the generator yields, the block nested in the
46\keyword{with} statement is executed. The generator is then resumed
47after the block is exited. If an unhandled exception occurs in the
48block, it is reraised inside the generator at the point where the yield
49occurred. Thus, you can use a
50\keyword{try}...\keyword{except}...\keyword{finally} statement to trap
Nick Coghlan877cf232006-04-24 04:17:02 +000051the error (if any), or ensure that some cleanup takes place. If an
52exception is trapped merely in order to log it or to perform some
53action (rather than to suppress it entirely), the generator must
54reraise that exception. Otherwise the \keyword{with} statement will
55treat the exception as having been handled, and resume execution with
56the statement immediately following the \keyword{with} statement.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000057\end{funcdesc}
58
59\begin{funcdesc}{nested}{ctx1\optional{, ctx2\optional{, ...}}}
Nick Coghlana7e820a2006-04-25 10:56:51 +000060Combine multiple context managers into a single nested context manager.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000061
62Code like this:
63
64\begin{verbatim}
65from contextlib import nested
66
67with nested(A, B, C) as (X, Y, Z):
68 do_something()
69\end{verbatim}
70
71is equivalent to this:
72
73\begin{verbatim}
74with A as X:
75 with B as Y:
76 with C as Z:
77 do_something()
78\end{verbatim}
79
Nick Coghlan877cf232006-04-24 04:17:02 +000080Note that if the \method{__exit__()} method of one of the nested
Nick Coghlana7e820a2006-04-25 10:56:51 +000081context objects indicates an exception should be suppressed, no
Nick Coghlan877cf232006-04-24 04:17:02 +000082exception information will be passed to any remaining outer context
Nick Coghlana7e820a2006-04-25 10:56:51 +000083objects. Similarly, if the \method{__exit__()} method of one of the
84nested context objects raises an exception, any previous exception
Nick Coghlan877cf232006-04-24 04:17:02 +000085state will be lost; the new exception will be passed to the
Nick Coghlana7e820a2006-04-25 10:56:51 +000086\method{__exit__()} methods of any remaining outer context objects.
Nick Coghlan877cf232006-04-24 04:17:02 +000087In general, \method{__exit__()} methods should avoid raising
88exceptions, and in particular they should not re-raise a
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000089passed-in exception.
90\end{funcdesc}
91
92\label{context-closing}
93\begin{funcdesc}{closing}{thing}
Nick Coghlana7e820a2006-04-25 10:56:51 +000094Return a context that closes \var{thing} upon completion of the
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000095block. This is basically equivalent to:
96
97\begin{verbatim}
Nick Coghlana7e820a2006-04-25 10:56:51 +000098from contextlib import contextfactory
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +000099
Nick Coghlana7e820a2006-04-25 10:56:51 +0000100@contextfactory
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000101def closing(thing):
102 try:
103 yield thing
104 finally:
105 thing.close()
106\end{verbatim}
107
108And lets you write code like this:
109\begin{verbatim}
Phillip J. Ebybdfd6932006-03-28 00:08:22 +0000110from __future__ import with_statement
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000111from contextlib import closing
Phillip J. Ebybdfd6932006-03-28 00:08:22 +0000112import codecs
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000113
Nick Coghlana7e820a2006-04-25 10:56:51 +0000114with closing(urllib.urlopen('http://www.python.org')) as page:
115 for line in page:
Nick Coghlan5ef9d9f2006-04-23 15:14:37 +0000116 print line
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000117\end{verbatim}
118
Nick Coghlana7e820a2006-04-25 10:56:51 +0000119without needing to explicitly close \code{page}. Even if an error
120occurs, \code{page.close()} will be called when the \keyword{with}
121block is exited.
Phillip J. Ebyd207b4f2006-03-27 23:58:46 +0000122\end{funcdesc}
123
124\begin{seealso}
125 \seepep{0343}{The "with" statement}
126 {The specification, background, and examples for the
127 Python \keyword{with} statement.}
128\end{seealso}