Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts. |
| 3 | ========================================================================= |
| 4 | |
| 5 | .. module:: contextlib |
| 6 | :synopsis: Utilities for with-statement contexts. |
| 7 | |
| 8 | |
| 9 | .. versionadded:: 2.5 |
| 10 | |
| 11 | This module provides utilities for common tasks involving the :keyword:`with` |
| 12 | statement. For more information see also :ref:`typecontextmanager` and |
| 13 | :ref:`context-managers`. |
| 14 | |
| 15 | Functions provided: |
| 16 | |
| 17 | |
| 18 | .. function:: contextmanager(func) |
| 19 | |
| 20 | This function is a decorator that can be used to define a factory function for |
| 21 | :keyword:`with` statement context managers, without needing to create a class or |
| 22 | separate :meth:`__enter__` and :meth:`__exit__` methods. |
| 23 | |
| 24 | A simple example (this is not recommended as a real way of generating HTML!):: |
| 25 | |
| 26 | from __future__ import with_statement |
| 27 | from contextlib import contextmanager |
| 28 | |
| 29 | @contextmanager |
| 30 | def tag(name): |
| 31 | print "<%s>" % name |
| 32 | yield |
| 33 | print "</%s>" % name |
| 34 | |
| 35 | >>> with tag("h1"): |
| 36 | ... print "foo" |
| 37 | ... |
| 38 | <h1> |
| 39 | foo |
| 40 | </h1> |
| 41 | |
| 42 | The function being decorated must return a generator-iterator when called. This |
| 43 | iterator must yield exactly one value, which will be bound to the targets in the |
| 44 | :keyword:`with` statement's :keyword:`as` clause, if any. |
| 45 | |
| 46 | At the point where the generator yields, the block nested in the :keyword:`with` |
| 47 | statement is executed. The generator is then resumed after the block is exited. |
| 48 | If an unhandled exception occurs in the block, it is reraised inside the |
| 49 | generator at the point where the yield occurred. Thus, you can use a |
| 50 | :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap |
| 51 | the error (if any), or ensure that some cleanup takes place. If an exception is |
| 52 | trapped merely in order to log it or to perform some action (rather than to |
| 53 | suppress it entirely), the generator must reraise that exception. Otherwise the |
| 54 | generator context manager will indicate to the :keyword:`with` statement that |
| 55 | the exception has been handled, and execution will resume with the statement |
| 56 | immediately following the :keyword:`with` statement. |
| 57 | |
| 58 | |
| 59 | .. function:: nested(mgr1[, mgr2[, ...]]) |
| 60 | |
| 61 | Combine multiple context managers into a single nested context manager. |
| 62 | |
| 63 | Code like this:: |
| 64 | |
| 65 | from contextlib import nested |
| 66 | |
| 67 | with nested(A, B, C) as (X, Y, Z): |
| 68 | do_something() |
| 69 | |
| 70 | is equivalent to this:: |
| 71 | |
| 72 | with A as X: |
| 73 | with B as Y: |
| 74 | with C as Z: |
| 75 | do_something() |
| 76 | |
| 77 | Note that if the :meth:`__exit__` method of one of the nested context managers |
| 78 | indicates an exception should be suppressed, no exception information will be |
| 79 | passed to any remaining outer context managers. Similarly, if the |
| 80 | :meth:`__exit__` method of one of the nested managers raises an exception, any |
| 81 | previous exception state will be lost; the new exception will be passed to the |
| 82 | :meth:`__exit__` methods of any remaining outer context managers. In general, |
| 83 | :meth:`__exit__` methods should avoid raising exceptions, and in particular they |
| 84 | should not re-raise a passed-in exception. |
| 85 | |
| 86 | |
| 87 | .. function:: closing(thing) |
| 88 | |
| 89 | Return a context manager that closes *thing* upon completion of the block. This |
| 90 | is basically equivalent to:: |
| 91 | |
| 92 | from contextlib import contextmanager |
| 93 | |
| 94 | @contextmanager |
| 95 | def closing(thing): |
| 96 | try: |
| 97 | yield thing |
| 98 | finally: |
| 99 | thing.close() |
| 100 | |
| 101 | And lets you write code like this:: |
| 102 | |
| 103 | from __future__ import with_statement |
| 104 | from contextlib import closing |
| 105 | import urllib |
| 106 | |
| 107 | with closing(urllib.urlopen('http://www.python.org')) as page: |
| 108 | for line in page: |
| 109 | print line |
| 110 | |
| 111 | without needing to explicitly close ``page``. Even if an error occurs, |
| 112 | ``page.close()`` will be called when the :keyword:`with` block is exited. |
| 113 | |
| 114 | |
| 115 | .. seealso:: |
| 116 | |
| 117 | :pep:`0343` - The "with" statement |
| 118 | The specification, background, and examples for the Python :keyword:`with` |
| 119 | statement. |
| 120 | |