Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +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 | |
| 7 | \versionadded{2.5} |
| 8 | |
| 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 |
| 49 | the error (if any), or ensure that some cleanup takes place. |
| 50 | |
| 51 | Note that you can use \code{@contextmanager} to define a context |
| 52 | manager's \method{__context__} method. This is usually more convenient |
| 53 | than creating another class just to serve as a context. For example: |
| 54 | |
| 55 | \begin{verbatim} |
| 56 | from __future__ import with_statement |
| 57 | from contextlib import contextmanager |
| 58 | |
| 59 | class 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 | |
| 69 | h1 = Tag("h1") |
| 70 | |
| 71 | >>> with h1 as me: |
| 72 | ... print "hello from", me |
| 73 | <h1> |
| 74 | hello from <__main__.Tag instance at 0x402ce8ec> |
| 75 | </h1> |
| 76 | \end{verbatim} |
| 77 | \end{funcdesc} |
| 78 | |
| 79 | \begin{funcdesc}{nested}{ctx1\optional{, ctx2\optional{, ...}}} |
| 80 | Combine multiple context managers into a single nested context manager. |
| 81 | |
| 82 | Code like this: |
| 83 | |
| 84 | \begin{verbatim} |
| 85 | from contextlib import nested |
| 86 | |
| 87 | with nested(A, B, C) as (X, Y, Z): |
| 88 | do_something() |
| 89 | \end{verbatim} |
| 90 | |
| 91 | is equivalent to this: |
| 92 | |
| 93 | \begin{verbatim} |
| 94 | with A as X: |
| 95 | with B as Y: |
| 96 | with C as Z: |
| 97 | do_something() |
| 98 | \end{verbatim} |
| 99 | |
| 100 | Note that if one of the nested contexts' \method{__exit__()} method |
| 101 | raises an exception, any previous exception state will be lost; the new |
| 102 | exception will be passed to the outer contexts' \method{__exit__()} |
| 103 | method(s), if any. In general, \method{__exit__()} methods should avoid |
| 104 | raising exceptions, and in particular they should not re-raise a |
| 105 | passed-in exception. |
| 106 | \end{funcdesc} |
| 107 | |
| 108 | \label{context-closing} |
| 109 | \begin{funcdesc}{closing}{thing} |
| 110 | Return a context manager that closes \var{thing} upon completion of the |
| 111 | block. This is basically equivalent to: |
| 112 | |
| 113 | \begin{verbatim} |
| 114 | from contextlib import contextmanager |
| 115 | |
| 116 | @contextmanager |
| 117 | def closing(thing): |
| 118 | try: |
| 119 | yield thing |
| 120 | finally: |
| 121 | thing.close() |
| 122 | \end{verbatim} |
| 123 | |
| 124 | And lets you write code like this: |
| 125 | \begin{verbatim} |
| 126 | from __future__ import with_statement |
| 127 | from contextlib import closing |
| 128 | import codecs |
| 129 | |
| 130 | with closing(codecs.open("foo", encoding="utf8")) as f: |
| 131 | for line in f: |
| 132 | print line.encode("latin1") |
| 133 | \end{verbatim} |
| 134 | |
| 135 | without 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} |