blob: c4350821b5eef094921e0e336525196d24e39f98 [file] [log] [blame]
Georg Brandl42a82642009-06-08 07:57:35 +00001:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
2========================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00003
4.. module:: contextlib
5 :synopsis: Utilities for with-statement contexts.
6
7
8.. versionadded:: 2.5
9
10This module provides utilities for common tasks involving the :keyword:`with`
11statement. For more information see also :ref:`typecontextmanager` and
12:ref:`context-managers`.
13
Raymond Hettingere0e08222010-11-06 07:10:31 +000014.. 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
Georg Brandl8ec7f652007-08-15 14:28:01 +000019Functions provided:
20
21
22.. function:: contextmanager(func)
23
Georg Brandl584265b2007-12-02 14:58:50 +000024 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28 A simple example (this is not recommended as a real way of generating HTML!)::
29
Georg Brandl8ec7f652007-08-15 14:28:01 +000030 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
Georg Brandlcf3fb252007-10-21 10:52:38 +000045 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +000048
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
Nick Coghlan7c2bc832009-06-17 12:12:15 +000066 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::
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
73 from contextlib import nested
74
Nick Coghlan7c2bc832009-06-17 12:12:15 +000075 with nested(*managers):
Georg Brandl8ec7f652007-08-15 14:28:01 +000076 do_something()
77
Georg Brandl8ec7f652007-08-15 14:28:01 +000078 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
Nick Coghlan7c2bc832009-06-17 12:12:15 +000087 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
Raymond Hettinger822b87f2009-05-29 01:46:48 +0000106 .. deprecated:: 2.7
Nick Coghlan7c2bc832009-06-17 12:12:15 +0000107 The with-statement now supports this functionality directly (without the
108 confusing error prone quirks).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000109
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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000126 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