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`.
16 Latest version of the `contextlib Python source code
17 <http://svn.python.org/view/python/branches/release27-maint/Lib/contextlib.py?view=markup>`_
22 .. function:: contextmanager(func)
24 This function is a :term:`decorator` that can be used to define a factory
25 function for :keyword:`with` statement context managers, without needing to
26 create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
28 A simple example (this is not recommended as a real way of generating HTML!)::
30 from contextlib import contextmanager
45 The function being decorated must return a :term:`generator`-iterator when
46 called. This iterator must yield exactly one value, which will be bound to
47 the targets in the :keyword:`with` statement's :keyword:`as` clause, if any.
49 At the point where the generator yields, the block nested in the :keyword:`with`
50 statement is executed. The generator is then resumed after the block is exited.
51 If an unhandled exception occurs in the block, it is reraised inside the
52 generator at the point where the yield occurred. Thus, you can use a
53 :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap
54 the error (if any), or ensure that some cleanup takes place. If an exception is
55 trapped merely in order to log it or to perform some action (rather than to
56 suppress it entirely), the generator must reraise that exception. Otherwise the
57 generator context manager will indicate to the :keyword:`with` statement that
58 the exception has been handled, and execution will resume with the statement
59 immediately following the :keyword:`with` statement.
62 .. function:: nested(mgr1[, mgr2[, ...]])
64 Combine multiple context managers into a single nested context manager.
66 This function has been deprecated in favour of the multiple manager form
67 of the :keyword:`with` statement.
69 The one advantage of this function over the multiple manager form of the
70 :keyword:`with` statement is that argument unpacking allows it to be
71 used with a variable number of context managers as follows::
73 from contextlib import nested
75 with nested(*managers):
78 Note that if the :meth:`__exit__` method of one of the nested context managers
79 indicates an exception should be suppressed, no exception information will be
80 passed to any remaining outer context managers. Similarly, if the
81 :meth:`__exit__` method of one of the nested managers raises an exception, any
82 previous exception state will be lost; the new exception will be passed to the
83 :meth:`__exit__` methods of any remaining outer context managers. In general,
84 :meth:`__exit__` methods should avoid raising exceptions, and in particular they
85 should not re-raise a passed-in exception.
87 This function has two major quirks that have led to it being deprecated. Firstly,
88 as the context managers are all constructed before the function is invoked, the
89 :meth:`__new__` and :meth:`__init__` methods of the inner context managers are
90 not actually covered by the scope of the outer context managers. That means, for
91 example, that using :func:`nested` to open two files is a programming error as the
92 first file will not be closed promptly if an exception is thrown when opening
95 Secondly, if the :meth:`__enter__` method of one of the inner context managers
96 raises an exception that is caught and suppressed by the :meth:`__exit__` method
97 of one of the outer context managers, this construct will raise
98 :exc:`RuntimeError` rather than skipping the body of the :keyword:`with`
101 Developers that need to support nesting of a variable number of context managers
102 can either use the :mod:`warnings` module to suppress the DeprecationWarning
103 raised by this function or else use this function as a model for an application
104 specific implementation.
107 The with-statement now supports this functionality directly (without the
108 confusing error prone quirks).
110 .. function:: closing(thing)
112 Return a context manager that closes *thing* upon completion of the block. This
113 is basically equivalent to::
115 from contextlib import contextmanager
124 And lets you write code like this::
126 from contextlib import closing
129 with closing(urllib.urlopen('http://www.python.org')) as page:
133 without needing to explicitly close ``page``. Even if an error occurs,
134 ``page.close()`` will be called when the :keyword:`with` block is exited.
139 :pep:`0343` - The "with" statement
140 The specification, background, and examples for the Python :keyword:`with`