blob: d28a11f9d1e72e0b3d772a034d595817b1635b3a [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
14Functions provided:
15
16
17.. function:: contextmanager(func)
18
Georg Brandl584265b2007-12-02 14:58:50 +000019 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +000022
23 A simple example (this is not recommended as a real way of generating HTML!)::
24
Georg Brandl8ec7f652007-08-15 14:28:01 +000025 from contextlib import contextmanager
26
27 @contextmanager
28 def tag(name):
29 print "<%s>" % name
30 yield
31 print "</%s>" % name
32
33 >>> with tag("h1"):
34 ... print "foo"
35 ...
36 <h1>
37 foo
38 </h1>
39
Georg Brandlcf3fb252007-10-21 10:52:38 +000040 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +000043
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.
55
56
57.. function:: nested(mgr1[, mgr2[, ...]])
58
59 Combine multiple context managers into a single nested context manager.
60
61 Code like this::
62
63 from contextlib import nested
64
Georg Brandl5a95b212009-03-15 21:44:43 +000065 with nested(A(), B(), C()) as (X, Y, Z):
Georg Brandl8ec7f652007-08-15 14:28:01 +000066 do_something()
67
68 is equivalent to this::
69
Georg Brandl5a95b212009-03-15 21:44:43 +000070 m1, m2, m3 = A(), B(), C()
71 with m1 as X:
72 with m2 as Y:
73 with m3 as Z:
Georg Brandl8ec7f652007-08-15 14:28:01 +000074 do_something()
75
76 Note that if the :meth:`__exit__` method of one of the nested context managers
77 indicates an exception should be suppressed, no exception information will be
78 passed to any remaining outer context managers. Similarly, if the
79 :meth:`__exit__` method of one of the nested managers raises an exception, any
80 previous exception state will be lost; the new exception will be passed to the
81 :meth:`__exit__` methods of any remaining outer context managers. In general,
82 :meth:`__exit__` methods should avoid raising exceptions, and in particular they
83 should not re-raise a passed-in exception.
84
Raymond Hettinger822b87f2009-05-29 01:46:48 +000085 .. deprecated:: 2.7
86 The with-statement now supports this functionality directly.
Georg Brandl8ec7f652007-08-15 14:28:01 +000087
88.. function:: closing(thing)
89
90 Return a context manager that closes *thing* upon completion of the block. This
91 is basically equivalent to::
92
93 from contextlib import contextmanager
94
95 @contextmanager
96 def closing(thing):
97 try:
98 yield thing
99 finally:
100 thing.close()
101
102 And lets you write code like this::
103
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104 from contextlib import closing
105 import urllib
106
107 with closing(urllib.urlopen('http://www.python.org')) as page:
108 for line in page:
109 print line
110
111 without needing to explicitly close ``page``. Even if an error occurs,
112 ``page.close()`` will be called when the :keyword:`with` block is exited.
113
114
115.. seealso::
116
117 :pep:`0343` - The "with" statement
118 The specification, background, and examples for the Python :keyword:`with`
119 statement.
120