Georg Brandl | 0eaab97 | 2009-06-08 08:00:22 +0000 | [diff] [blame] | 1 | :mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts |
| 2 | ======================================================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: contextlib |
| 5 | :synopsis: Utilities for with-statement contexts. |
| 6 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 7 | **Source code:** :source:`Lib/contextlib.py` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 8 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 9 | -------------- |
| 10 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 18 | .. decorator:: contextmanager |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 19 | |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 20 | This function is a :term:`decorator` that can be used to define a factory |
| 21 | function for :keyword:`with` statement context managers, without needing to |
| 22 | create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 23 | |
| 24 | A simple example (this is not recommended as a real way of generating HTML!):: |
| 25 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | from contextlib import contextmanager |
| 27 | |
| 28 | @contextmanager |
| 29 | def tag(name): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 30 | print("<%s>" % name) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | yield |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 32 | print("</%s>" % name) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 33 | |
| 34 | >>> with tag("h1"): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 35 | ... print("foo") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | ... |
| 37 | <h1> |
| 38 | foo |
| 39 | </h1> |
| 40 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 41 | The function being decorated must return a :term:`generator`-iterator when |
| 42 | called. This iterator must yield exactly one value, which will be bound to |
| 43 | the targets in the :keyword:`with` statement's :keyword:`as` clause, if any. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 44 | |
| 45 | At the point where the generator yields, the block nested in the :keyword:`with` |
| 46 | statement is executed. The generator is then resumed after the block is exited. |
| 47 | If an unhandled exception occurs in the block, it is reraised inside the |
| 48 | generator at the point where the yield occurred. Thus, you can use a |
| 49 | :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap |
| 50 | the error (if any), or ensure that some cleanup takes place. If an exception is |
| 51 | trapped merely in order to log it or to perform some action (rather than to |
| 52 | suppress it entirely), the generator must reraise that exception. Otherwise the |
| 53 | generator context manager will indicate to the :keyword:`with` statement that |
| 54 | the exception has been handled, and execution will resume with the statement |
| 55 | immediately following the :keyword:`with` statement. |
| 56 | |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 57 | :func:`contextmanager` uses :class:`ContextDecorator` so the context managers |
| 58 | it creates can be used as decorators as well as in :keyword:`with` statements. |
| 59 | When used as a decorator, a new generator instance is implicitly created on |
| 60 | each function call (this allows the otherwise "one-shot" context managers |
| 61 | created by :func:`contextmanager` to meet the requirement that context |
| 62 | managers support multiple invocations in order to be used as decorators). |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 63 | |
| 64 | .. versionchanged:: 3.2 |
| 65 | Use of :class:`ContextDecorator`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 66 | |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 67 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 68 | .. function:: closing(thing) |
| 69 | |
| 70 | Return a context manager that closes *thing* upon completion of the block. This |
| 71 | is basically equivalent to:: |
| 72 | |
| 73 | from contextlib import contextmanager |
| 74 | |
| 75 | @contextmanager |
| 76 | def closing(thing): |
| 77 | try: |
| 78 | yield thing |
| 79 | finally: |
| 80 | thing.close() |
| 81 | |
| 82 | And lets you write code like this:: |
| 83 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 84 | from contextlib import closing |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 85 | from urllib.request import urlopen |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 86 | |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 87 | with closing(urlopen('http://www.python.org')) as page: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | for line in page: |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 89 | print(line) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 90 | |
| 91 | without needing to explicitly close ``page``. Even if an error occurs, |
| 92 | ``page.close()`` will be called when the :keyword:`with` block is exited. |
| 93 | |
| 94 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 95 | .. class:: ContextDecorator() |
| 96 | |
| 97 | A base class that enables a context manager to also be used as a decorator. |
| 98 | |
| 99 | Context managers inheriting from ``ContextDecorator`` have to implement |
| 100 | ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional |
| 101 | exception handling even when used as a decorator. |
| 102 | |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 103 | ``ContextDecorator`` is used by :func:`contextmanager`, so you get this |
| 104 | functionality automatically. |
| 105 | |
| 106 | Example of ``ContextDecorator``:: |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 107 | |
| 108 | from contextlib import ContextDecorator |
| 109 | |
| 110 | class mycontext(ContextDecorator): |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 111 | def __enter__(self): |
| 112 | print('Starting') |
| 113 | return self |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 114 | |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 115 | def __exit__(self, *exc): |
| 116 | print('Finishing') |
| 117 | return False |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 118 | |
| 119 | >>> @mycontext() |
| 120 | ... def function(): |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 121 | ... print('The bit in the middle') |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 122 | ... |
| 123 | >>> function() |
| 124 | Starting |
| 125 | The bit in the middle |
| 126 | Finishing |
| 127 | |
| 128 | >>> with mycontext(): |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 129 | ... print('The bit in the middle') |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 130 | ... |
| 131 | Starting |
| 132 | The bit in the middle |
| 133 | Finishing |
| 134 | |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 135 | This change is just syntactic sugar for any construct of the following form:: |
| 136 | |
| 137 | def f(): |
| 138 | with cm(): |
| 139 | # Do stuff |
| 140 | |
| 141 | ``ContextDecorator`` lets you instead write:: |
| 142 | |
| 143 | @cm() |
| 144 | def f(): |
| 145 | # Do stuff |
| 146 | |
| 147 | It makes it clear that the ``cm`` applies to the whole function, rather than |
| 148 | just a piece of it (and saving an indentation level is nice, too). |
| 149 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 150 | Existing context managers that already have a base class can be extended by |
| 151 | using ``ContextDecorator`` as a mixin class:: |
| 152 | |
| 153 | from contextlib import ContextDecorator |
| 154 | |
| 155 | class mycontext(ContextBaseClass, ContextDecorator): |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 156 | def __enter__(self): |
| 157 | return self |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 158 | |
Georg Brandl | 86e78d1 | 2010-07-18 13:43:32 +0000 | [diff] [blame] | 159 | def __exit__(self, *exc): |
| 160 | return False |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 161 | |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 162 | .. note:: |
| 163 | As the decorated function must be able to be called multiple times, the |
| 164 | underlying context manager must support use in multiple :keyword:`with` |
| 165 | statements. If this is not the case, then the original construct with the |
| 166 | explicit :keyword:`with` statement inside the function should be used. |
| 167 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 168 | .. versionadded:: 3.2 |
| 169 | |
| 170 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | .. seealso:: |
| 172 | |
| 173 | :pep:`0343` - The "with" statement |
| 174 | The specification, background, and examples for the Python :keyword:`with` |
| 175 | statement. |
| 176 | |