blob: 935afeeba907295b3d0ee06d16d97714b3fb06f7 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts.
3=========================================================================
4
5.. module:: contextlib
6 :synopsis: Utilities for with-statement contexts.
7
8
9.. versionadded:: 2.5
10
11This module provides utilities for common tasks involving the :keyword:`with`
12statement. For more information see also :ref:`typecontextmanager` and
13:ref:`context-managers`.
14
15Functions provided:
16
17
18.. function:: contextmanager(func)
19
Georg Brandl584265b2007-12-02 14:58:50 +000020 This function is a :term:`decorator` that can be used to define a factory
21 function for :keyword:`with` statement context managers, without needing to
22 create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +000023
24 A simple example (this is not recommended as a real way of generating HTML!)::
25
Georg Brandl8ec7f652007-08-15 14:28:01 +000026 from contextlib import contextmanager
27
28 @contextmanager
29 def tag(name):
30 print "<%s>" % name
31 yield
32 print "</%s>" % name
33
34 >>> with tag("h1"):
35 ... print "foo"
36 ...
37 <h1>
38 foo
39 </h1>
40
Georg Brandlcf3fb252007-10-21 10:52:38 +000041 The function being decorated must return a :term:`generator`-iterator when
42 called. This iterator must yield exactly one value, which will be bound to
43 the targets in the :keyword:`with` statement's :keyword:`as` clause, if any.
Georg Brandl8ec7f652007-08-15 14:28:01 +000044
45 At the point where the generator yields, the block nested in the :keyword:`with`
46 statement is executed. The generator is then resumed after the block is exited.
47 If an unhandled exception occurs in the block, it is reraised inside the
48 generator at the point where the yield occurred. Thus, you can use a
49 :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap
50 the error (if any), or ensure that some cleanup takes place. If an exception is
51 trapped merely in order to log it or to perform some action (rather than to
52 suppress it entirely), the generator must reraise that exception. Otherwise the
53 generator context manager will indicate to the :keyword:`with` statement that
54 the exception has been handled, and execution will resume with the statement
55 immediately following the :keyword:`with` statement.
56
57
58.. function:: nested(mgr1[, mgr2[, ...]])
59
60 Combine multiple context managers into a single nested context manager.
61
62 Code like this::
63
64 from contextlib import nested
65
Georg Brandl5a95b212009-03-15 21:44:43 +000066 with nested(A(), B(), C()) as (X, Y, Z):
Georg Brandl8ec7f652007-08-15 14:28:01 +000067 do_something()
68
69 is equivalent to this::
70
Georg Brandl5a95b212009-03-15 21:44:43 +000071 m1, m2, m3 = A(), B(), C()
72 with m1 as X:
73 with m2 as Y:
74 with m3 as Z:
Georg Brandl8ec7f652007-08-15 14:28:01 +000075 do_something()
76
77 Note that if the :meth:`__exit__` method of one of the nested context managers
78 indicates an exception should be suppressed, no exception information will be
79 passed to any remaining outer context managers. Similarly, if the
80 :meth:`__exit__` method of one of the nested managers raises an exception, any
81 previous exception state will be lost; the new exception will be passed to the
82 :meth:`__exit__` methods of any remaining outer context managers. In general,
83 :meth:`__exit__` methods should avoid raising exceptions, and in particular they
84 should not re-raise a passed-in exception.
85
86
87.. function:: closing(thing)
88
89 Return a context manager that closes *thing* upon completion of the block. This
90 is basically equivalent to::
91
92 from contextlib import contextmanager
93
94 @contextmanager
95 def closing(thing):
96 try:
97 yield thing
98 finally:
99 thing.close()
100
101 And lets you write code like this::
102
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103 from contextlib import closing
104 import urllib
105
106 with closing(urllib.urlopen('http://www.python.org')) as page:
107 for line in page:
108 print line
109
110 without needing to explicitly close ``page``. Even if an error occurs,
111 ``page.close()`` will be called when the :keyword:`with` block is exited.
112
113
114.. seealso::
115
116 :pep:`0343` - The "with" statement
117 The specification, background, and examples for the Python :keyword:`with`
118 statement.
119