Georg Brandl | 42a8264 | 2009-06-08 07:57:35 +0000 | [diff] [blame] | 1 | :mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts |
| 2 | ======================================================================== |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: contextlib |
| 5 | :synopsis: Utilities for with-statement contexts. |
| 6 | |
| 7 | |
| 8 | .. versionadded:: 2.5 |
| 9 | |
| 10 | This module provides utilities for common tasks involving the :keyword:`with` |
| 11 | statement. For more information see also :ref:`typecontextmanager` and |
| 12 | :ref:`context-managers`. |
| 13 | |
| 14 | Functions provided: |
| 15 | |
| 16 | |
| 17 | .. function:: contextmanager(func) |
| 18 | |
Georg Brandl | 584265b | 2007-12-02 14:58:50 +0000 | [diff] [blame] | 19 | This function is a :term:`decorator` that can be used to define a factory |
| 20 | function for :keyword:`with` statement context managers, without needing to |
| 21 | create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 22 | |
| 23 | A simple example (this is not recommended as a real way of generating HTML!):: |
| 24 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 25 | from contextlib import contextmanager |
| 26 | |
| 27 | @contextmanager |
| 28 | def tag(name): |
| 29 | print "<%s>" % name |
| 30 | yield |
| 31 | print "</%s>" % name |
| 32 | |
| 33 | >>> with tag("h1"): |
| 34 | ... print "foo" |
| 35 | ... |
| 36 | <h1> |
| 37 | foo |
| 38 | </h1> |
| 39 | |
Georg Brandl | cf3fb25 | 2007-10-21 10:52:38 +0000 | [diff] [blame] | 40 | The function being decorated must return a :term:`generator`-iterator when |
| 41 | called. This iterator must yield exactly one value, which will be bound to |
| 42 | the targets in the :keyword:`with` statement's :keyword:`as` clause, if any. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 43 | |
| 44 | At the point where the generator yields, the block nested in the :keyword:`with` |
| 45 | statement is executed. The generator is then resumed after the block is exited. |
| 46 | If an unhandled exception occurs in the block, it is reraised inside the |
| 47 | generator at the point where the yield 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. If an exception is |
| 50 | trapped merely in order to log it or to perform some action (rather than to |
| 51 | suppress it entirely), the generator must reraise that exception. Otherwise the |
| 52 | generator context manager will indicate to the :keyword:`with` statement that |
| 53 | the exception has been handled, and execution will resume with the statement |
| 54 | immediately following the :keyword:`with` statement. |
| 55 | |
| 56 | |
| 57 | .. function:: nested(mgr1[, mgr2[, ...]]) |
| 58 | |
| 59 | Combine multiple context managers into a single nested context manager. |
| 60 | |
Nick Coghlan | 7c2bc83 | 2009-06-17 12:12:15 +0000 | [diff] [blame^] | 61 | This function has been deprecated in favour of the multiple manager form |
| 62 | of the :keyword:`with` statement. |
| 63 | |
| 64 | The one advantage of this function over the multiple manager form of the |
| 65 | :keyword:`with` statement is that argument unpacking allows it to be |
| 66 | used with a variable number of context managers as follows:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 67 | |
| 68 | from contextlib import nested |
| 69 | |
Nick Coghlan | 7c2bc83 | 2009-06-17 12:12:15 +0000 | [diff] [blame^] | 70 | with nested(*managers): |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 71 | do_something() |
| 72 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 73 | Note that if the :meth:`__exit__` method of one of the nested context managers |
| 74 | indicates an exception should be suppressed, no exception information will be |
| 75 | passed to any remaining outer context managers. Similarly, if the |
| 76 | :meth:`__exit__` method of one of the nested managers raises an exception, any |
| 77 | previous exception state will be lost; the new exception will be passed to the |
| 78 | :meth:`__exit__` methods of any remaining outer context managers. In general, |
| 79 | :meth:`__exit__` methods should avoid raising exceptions, and in particular they |
| 80 | should not re-raise a passed-in exception. |
| 81 | |
Nick Coghlan | 7c2bc83 | 2009-06-17 12:12:15 +0000 | [diff] [blame^] | 82 | This function has two major quirks that have led to it being deprecated. Firstly, |
| 83 | as the context managers are all constructed before the function is invoked, the |
| 84 | :meth:`__new__` and :meth:`__init__` methods of the inner context managers are |
| 85 | not actually covered by the scope of the outer context managers. That means, for |
| 86 | example, that using :func:`nested` to open two files is a programming error as the |
| 87 | first file will not be closed promptly if an exception is thrown when opening |
| 88 | the second file. |
| 89 | |
| 90 | Secondly, if the :meth:`__enter__` method of one of the inner context managers |
| 91 | raises an exception that is caught and suppressed by the :meth:`__exit__` method |
| 92 | of one of the outer context managers, this construct will raise |
| 93 | :exc:`RuntimeError` rather than skipping the body of the :keyword:`with` |
| 94 | statement. |
| 95 | |
| 96 | Developers that need to support nesting of a variable number of context managers |
| 97 | can either use the :mod:`warnings` module to suppress the DeprecationWarning |
| 98 | raised by this function or else use this function as a model for an application |
| 99 | specific implementation. |
| 100 | |
Raymond Hettinger | 822b87f | 2009-05-29 01:46:48 +0000 | [diff] [blame] | 101 | .. deprecated:: 2.7 |
Nick Coghlan | 7c2bc83 | 2009-06-17 12:12:15 +0000 | [diff] [blame^] | 102 | The with-statement now supports this functionality directly (without the |
| 103 | confusing error prone quirks). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 104 | |
| 105 | .. function:: closing(thing) |
| 106 | |
| 107 | Return a context manager that closes *thing* upon completion of the block. This |
| 108 | is basically equivalent to:: |
| 109 | |
| 110 | from contextlib import contextmanager |
| 111 | |
| 112 | @contextmanager |
| 113 | def closing(thing): |
| 114 | try: |
| 115 | yield thing |
| 116 | finally: |
| 117 | thing.close() |
| 118 | |
| 119 | And lets you write code like this:: |
| 120 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 121 | from contextlib import closing |
| 122 | import urllib |
| 123 | |
| 124 | with closing(urllib.urlopen('http://www.python.org')) as page: |
| 125 | for line in page: |
| 126 | print line |
| 127 | |
| 128 | without needing to explicitly close ``page``. Even if an error occurs, |
| 129 | ``page.close()`` will be called when the :keyword:`with` block is exited. |
| 130 | |
| 131 | |
| 132 | .. seealso:: |
| 133 | |
| 134 | :pep:`0343` - The "with" statement |
| 135 | The specification, background, and examples for the Python :keyword:`with` |
| 136 | statement. |
| 137 | |