blob: a35ea569c17221724c944aa79265778fb87d45cd [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
Raymond Hettinger10480942011-01-10 03:26:08 +00007**Source code:** :source:`Lib/contextlib.py`
Georg Brandl116aa622007-08-15 14:28:22 +00008
Raymond Hettinger4f707fd2011-01-10 19:54:11 +00009--------------
10
Georg Brandl116aa622007-08-15 14:28:22 +000011This 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
Georg Brandl8a1caa22010-07-29 16:01:11 +000018.. decorator:: contextmanager
Georg Brandl116aa622007-08-15 14:28:22 +000019
Christian Heimesd8654cf2007-12-02 15:22:16 +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 Brandl116aa622007-08-15 14:28:22 +000023
24 A simple example (this is not recommended as a real way of generating HTML!)::
25
Georg Brandl116aa622007-08-15 14:28:22 +000026 from contextlib import contextmanager
27
28 @contextmanager
29 def tag(name):
Georg Brandl6911e3c2007-09-04 07:15:32 +000030 print("<%s>" % name)
Georg Brandl116aa622007-08-15 14:28:22 +000031 yield
Georg Brandl6911e3c2007-09-04 07:15:32 +000032 print("</%s>" % name)
Georg Brandl116aa622007-08-15 14:28:22 +000033
34 >>> with tag("h1"):
Georg Brandl6911e3c2007-09-04 07:15:32 +000035 ... print("foo")
Georg Brandl116aa622007-08-15 14:28:22 +000036 ...
37 <h1>
38 foo
39 </h1>
40
Georg Brandl9afde1c2007-11-01 20:32:30 +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 Brandl116aa622007-08-15 14:28:22 +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
Michael Foordb3a89842010-06-30 12:17:50 +000057 contextmanager uses :class:`ContextDecorator` so the context managers it
58 creates can be used as decorators as well as in :keyword:`with` statements.
59
60 .. versionchanged:: 3.2
61 Use of :class:`ContextDecorator`.
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandl86e78d12010-07-18 13:43:32 +000063
Georg Brandl116aa622007-08-15 14:28:22 +000064.. function:: closing(thing)
65
66 Return a context manager that closes *thing* upon completion of the block. This
67 is basically equivalent to::
68
69 from contextlib import contextmanager
70
71 @contextmanager
72 def closing(thing):
73 try:
74 yield thing
75 finally:
76 thing.close()
77
78 And lets you write code like this::
79
Georg Brandl116aa622007-08-15 14:28:22 +000080 from contextlib import closing
Georg Brandl0f7ede42008-06-23 11:23:31 +000081 from urllib.request import urlopen
Georg Brandl116aa622007-08-15 14:28:22 +000082
Georg Brandl0f7ede42008-06-23 11:23:31 +000083 with closing(urlopen('http://www.python.org')) as page:
Georg Brandl116aa622007-08-15 14:28:22 +000084 for line in page:
Georg Brandl6911e3c2007-09-04 07:15:32 +000085 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +000086
87 without needing to explicitly close ``page``. Even if an error occurs,
88 ``page.close()`` will be called when the :keyword:`with` block is exited.
89
90
Michael Foordb3a89842010-06-30 12:17:50 +000091.. class:: ContextDecorator()
92
93 A base class that enables a context manager to also be used as a decorator.
94
95 Context managers inheriting from ``ContextDecorator`` have to implement
96 ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional
97 exception handling even when used as a decorator.
98
Georg Brandl86e78d12010-07-18 13:43:32 +000099 ``ContextDecorator`` is used by :func:`contextmanager`, so you get this
100 functionality automatically.
101
102 Example of ``ContextDecorator``::
Michael Foordb3a89842010-06-30 12:17:50 +0000103
104 from contextlib import ContextDecorator
105
106 class mycontext(ContextDecorator):
Georg Brandl86e78d12010-07-18 13:43:32 +0000107 def __enter__(self):
108 print('Starting')
109 return self
Michael Foordb3a89842010-06-30 12:17:50 +0000110
Georg Brandl86e78d12010-07-18 13:43:32 +0000111 def __exit__(self, *exc):
112 print('Finishing')
113 return False
Michael Foordb3a89842010-06-30 12:17:50 +0000114
115 >>> @mycontext()
116 ... def function():
Georg Brandl86e78d12010-07-18 13:43:32 +0000117 ... print('The bit in the middle')
Michael Foordb3a89842010-06-30 12:17:50 +0000118 ...
119 >>> function()
120 Starting
121 The bit in the middle
122 Finishing
123
124 >>> with mycontext():
Georg Brandl86e78d12010-07-18 13:43:32 +0000125 ... print('The bit in the middle')
Michael Foordb3a89842010-06-30 12:17:50 +0000126 ...
127 Starting
128 The bit in the middle
129 Finishing
130
Georg Brandl86e78d12010-07-18 13:43:32 +0000131 This change is just syntactic sugar for any construct of the following form::
132
133 def f():
134 with cm():
135 # Do stuff
136
137 ``ContextDecorator`` lets you instead write::
138
139 @cm()
140 def f():
141 # Do stuff
142
143 It makes it clear that the ``cm`` applies to the whole function, rather than
144 just a piece of it (and saving an indentation level is nice, too).
145
Michael Foordb3a89842010-06-30 12:17:50 +0000146 Existing context managers that already have a base class can be extended by
147 using ``ContextDecorator`` as a mixin class::
148
149 from contextlib import ContextDecorator
150
151 class mycontext(ContextBaseClass, ContextDecorator):
Georg Brandl86e78d12010-07-18 13:43:32 +0000152 def __enter__(self):
153 return self
Michael Foordb3a89842010-06-30 12:17:50 +0000154
Georg Brandl86e78d12010-07-18 13:43:32 +0000155 def __exit__(self, *exc):
156 return False
Michael Foordb3a89842010-06-30 12:17:50 +0000157
158 .. versionadded:: 3.2
159
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161.. seealso::
162
163 :pep:`0343` - The "with" statement
164 The specification, background, and examples for the Python :keyword:`with`
165 statement.
166