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