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