blob: 7a46834a13e69a2a3abb960b7fefb495e0680ccb [file] [log] [blame]
Georg Brandl0eaab972009-06-08 08:00:22 +00001:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
2========================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: contextlib
5 :synopsis: Utilities for with-statement contexts.
6
7
Georg Brandl116aa622007-08-15 14:28:22 +00008This module provides utilities for common tasks involving the :keyword:`with`
9statement. For more information see also :ref:`typecontextmanager` and
10:ref:`context-managers`.
11
12Functions provided:
13
14
15.. function:: contextmanager(func)
16
Christian Heimesd8654cf2007-12-02 15:22:16 +000017 This function is a :term:`decorator` that can be used to define a factory
18 function for :keyword:`with` statement context managers, without needing to
19 create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +000020
21 A simple example (this is not recommended as a real way of generating HTML!)::
22
Georg Brandl116aa622007-08-15 14:28:22 +000023 from contextlib import contextmanager
24
25 @contextmanager
26 def tag(name):
Georg Brandl6911e3c2007-09-04 07:15:32 +000027 print("<%s>" % name)
Georg Brandl116aa622007-08-15 14:28:22 +000028 yield
Georg Brandl6911e3c2007-09-04 07:15:32 +000029 print("</%s>" % name)
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 >>> with tag("h1"):
Georg Brandl6911e3c2007-09-04 07:15:32 +000032 ... print("foo")
Georg Brandl116aa622007-08-15 14:28:22 +000033 ...
34 <h1>
35 foo
36 </h1>
37
Georg Brandl9afde1c2007-11-01 20:32:30 +000038 The function being decorated must return a :term:`generator`-iterator when
39 called. This iterator must yield exactly one value, which will be bound to
40 the targets in the :keyword:`with` statement's :keyword:`as` clause, if any.
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 At the point where the generator yields, the block nested in the :keyword:`with`
43 statement is executed. The generator is then resumed after the block is exited.
44 If an unhandled exception occurs in the block, it is reraised inside the
45 generator at the point where the yield occurred. Thus, you can use a
46 :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap
47 the error (if any), or ensure that some cleanup takes place. If an exception is
48 trapped merely in order to log it or to perform some action (rather than to
49 suppress it entirely), the generator must reraise that exception. Otherwise the
50 generator context manager will indicate to the :keyword:`with` statement that
51 the exception has been handled, and execution will resume with the statement
52 immediately following the :keyword:`with` statement.
53
Michael Foordb3a89842010-06-30 12:17:50 +000054 contextmanager uses :class:`ContextDecorator` so the context managers it
55 creates can be used as decorators as well as in :keyword:`with` statements.
56
57 .. versionchanged:: 3.2
58 Use of :class:`ContextDecorator`.
Georg Brandl116aa622007-08-15 14:28:22 +000059
Georg Brandl116aa622007-08-15 14:28:22 +000060.. function:: closing(thing)
61
62 Return a context manager that closes *thing* upon completion of the block. This
63 is basically equivalent to::
64
65 from contextlib import contextmanager
66
67 @contextmanager
68 def closing(thing):
69 try:
70 yield thing
71 finally:
72 thing.close()
73
74 And lets you write code like this::
75
Georg Brandl116aa622007-08-15 14:28:22 +000076 from contextlib import closing
Georg Brandl0f7ede42008-06-23 11:23:31 +000077 from urllib.request import urlopen
Georg Brandl116aa622007-08-15 14:28:22 +000078
Georg Brandl0f7ede42008-06-23 11:23:31 +000079 with closing(urlopen('http://www.python.org')) as page:
Georg Brandl116aa622007-08-15 14:28:22 +000080 for line in page:
Georg Brandl6911e3c2007-09-04 07:15:32 +000081 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 without needing to explicitly close ``page``. Even if an error occurs,
84 ``page.close()`` will be called when the :keyword:`with` block is exited.
85
86
Michael Foordb3a89842010-06-30 12:17:50 +000087.. class:: ContextDecorator()
88
89 A base class that enables a context manager to also be used as a decorator.
90
91 Context managers inheriting from ``ContextDecorator`` have to implement
92 ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional
93 exception handling even when used as a decorator.
94
95 Example::
96
97 from contextlib import ContextDecorator
98
99 class mycontext(ContextDecorator):
100 def __enter__(self):
101 print('Starting')
102 return self
103
104 def __exit__(self, *exc):
105 print('Finishing')
106 return False
107
108 >>> @mycontext()
109 ... def function():
110 ... print('The bit in the middle')
111 ...
112 >>> function()
113 Starting
114 The bit in the middle
115 Finishing
116
117 >>> with mycontext():
118 ... print('The bit in the middle')
119 ...
120 Starting
121 The bit in the middle
122 Finishing
123
124 Existing context managers that already have a base class can be extended by
125 using ``ContextDecorator`` as a mixin class::
126
127 from contextlib import ContextDecorator
128
129 class mycontext(ContextBaseClass, ContextDecorator):
130 def __enter__(self):
131 return self
132
133 def __exit__(self, *exc):
134 return False
135
136 .. versionadded:: 3.2
137
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139.. seealso::
140
141 :pep:`0343` - The "with" statement
142 The specification, background, and examples for the Python :keyword:`with`
143 statement.
144