1 :mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
2 ========================================================================
5 :synopsis: Utilities for with-statement contexts.
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`.
17 .. function:: contextmanager(func)
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.
23 A simple example (this is not recommended as a real way of generating HTML!)::
25 from contextlib import contextmanager
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.
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.
57 .. function:: nested(mgr1[, mgr2[, ...]])
59 Combine multiple context managers into a single nested context manager.
61 This function has been deprecated in favour of the multiple manager form
62 of the :keyword:`with` statement.
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::
68 from contextlib import nested
70 with nested(*managers):
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.
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
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`
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.
102 The with-statement now supports this functionality directly (without the
103 confusing error prone quirks).
105 .. function:: closing(thing)
107 Return a context manager that closes *thing* upon completion of the block. This
108 is basically equivalent to::
110 from contextlib import contextmanager
119 And lets you write code like this::
121 from contextlib import closing
124 with closing(urllib.urlopen('http://www.python.org')) as page:
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.
134 :pep:`0343` - The "with" statement
135 The specification, background, and examples for the Python :keyword:`with`