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