blob: 74a68cfc82fde5be33ef44cab0346d7fd29cef43 [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
64 with nested(A, B, C) as (X, Y, Z):
65 do_something()
66
67 is equivalent to this::
68
69 with A as X:
70 with B as Y:
71 with C as Z:
72 do_something()
73
74 Note that if the :meth:`__exit__` method of one of the nested context managers
75 indicates an exception should be suppressed, no exception information will be
76 passed to any remaining outer context managers. Similarly, if the
77 :meth:`__exit__` method of one of the nested managers raises an exception, any
78 previous exception state will be lost; the new exception will be passed to the
79 :meth:`__exit__` methods of any remaining outer context managers. In general,
80 :meth:`__exit__` methods should avoid raising exceptions, and in particular they
81 should not re-raise a passed-in exception.
82
83
84.. function:: closing(thing)
85
86 Return a context manager that closes *thing* upon completion of the block. This
87 is basically equivalent to::
88
89 from contextlib import contextmanager
90
91 @contextmanager
92 def closing(thing):
93 try:
94 yield thing
95 finally:
96 thing.close()
97
98 And lets you write code like this::
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100 from contextlib import closing
Georg Brandl0f7ede42008-06-23 11:23:31 +0000101 from urllib.request import urlopen
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Georg Brandl0f7ede42008-06-23 11:23:31 +0000103 with closing(urlopen('http://www.python.org')) as page:
Georg Brandl116aa622007-08-15 14:28:22 +0000104 for line in page:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000105 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 without needing to explicitly close ``page``. Even if an error occurs,
108 ``page.close()`` will be called when the :keyword:`with` block is exited.
109
110
111.. seealso::
112
113 :pep:`0343` - The "with" statement
114 The specification, background, and examples for the Python :keyword:`with`
115 statement.
116