c4350821b5eef094921e0e336525196d24e39f98
[profile/ivi/python.git] / Doc / library / contextlib.rst
1 :mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
2 ========================================================================
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 .. seealso::
15
16    Latest version of the `contextlib Python source code
17    <http://svn.python.org/view/python/branches/release27-maint/Lib/contextlib.py?view=markup>`_
18
19 Functions provided:
20
21
22 .. function:: contextmanager(func)
23
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.
27
28    A simple example (this is not recommended as a real way of generating HTML!)::
29
30       from contextlib import contextmanager
31
32       @contextmanager
33       def tag(name):
34           print "<%s>" % name
35           yield
36           print "</%s>" % name
37
38       >>> with tag("h1"):
39       ...    print "foo"
40       ...
41       <h1>
42       foo
43       </h1>
44
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.
48
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.
60
61
62 .. function:: nested(mgr1[, mgr2[, ...]])
63
64    Combine multiple context managers into a single nested context manager.
65
66    This function has been deprecated in favour of the multiple manager form
67    of the :keyword:`with` statement.
68
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::
72
73       from contextlib import nested
74
75       with nested(*managers):
76           do_something()
77
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.
86
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
93    the second file.
94
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`
99    statement.
100
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.
105
106    .. deprecated:: 2.7
107       The with-statement now supports this functionality directly (without the
108       confusing error prone quirks).
109
110 .. function:: closing(thing)
111
112    Return a context manager that closes *thing* upon completion of the block.  This
113    is basically equivalent to::
114
115       from contextlib import contextmanager
116
117       @contextmanager
118       def closing(thing):
119           try:
120               yield thing
121           finally:
122               thing.close()
123
124    And lets you write code like this::
125
126       from contextlib import closing
127       import urllib
128
129       with closing(urllib.urlopen('http://www.python.org')) as page:
130           for line in page:
131               print line
132
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.
135
136
137 .. seealso::
138
139    :pep:`0343` - The "with" statement
140       The specification, background, and examples for the Python :keyword:`with`
141       statement.
142