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