blob: 3dbf3a8f13da74e7b10afba8eb26a1576d979f14 [file] [log] [blame]
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001: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
Georg Brandl116aa622007-08-15 14:28:22 +000015
Nick Coghlan3267a302012-05-21 22:54:43 +100016Utilities
17---------
18
19Functions and classes provided:
Georg Brandl116aa622007-08-15 14:28:22 +000020
Brett Cannon9e080e02016-04-08 12:15:27 -070021.. class:: AbstractContextManager
22
Brett Cannon516f5462016-06-09 15:55:52 -070023 An :term:`abstract base class` for classes that implement
Brett Cannon9e080e02016-04-08 12:15:27 -070024 :meth:`object.__enter__` and :meth:`object.__exit__`. A default
25 implementation for :meth:`object.__enter__` is provided which returns
26 ``self`` while :meth:`object.__exit__` is an abstract method which by default
27 returns ``None``. See also the definition of :ref:`typecontextmanager`.
28
29 .. versionadded:: 3.6
30
31
Jelle Zijlstra176baa32017-12-13 17:19:17 -080032.. class:: AbstractAsyncContextManager
33
34 An :term:`abstract base class` for classes that implement
35 :meth:`object.__aenter__` and :meth:`object.__aexit__`. A default
36 implementation for :meth:`object.__aenter__` is provided which returns
37 ``self`` while :meth:`object.__aexit__` is an abstract method which by default
38 returns ``None``. See also the definition of
39 :ref:`async-context-managers`.
40
41 .. versionadded:: 3.7
42
Brett Cannon9e080e02016-04-08 12:15:27 -070043
Georg Brandl8a1caa22010-07-29 16:01:11 +000044.. decorator:: contextmanager
Georg Brandl116aa622007-08-15 14:28:22 +000045
Christian Heimesd8654cf2007-12-02 15:22:16 +000046 This function is a :term:`decorator` that can be used to define a factory
47 function for :keyword:`with` statement context managers, without needing to
48 create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +000049
Matthias Bussonnierbde782b2018-07-23 14:10:56 -070050 While many objects natively support use in with statements, sometimes a
51 resource needs to be managed that isn't a context manager in its own right,
52 and doesn't implement a ``close()`` method for use with ``contextlib.closing``
53
54 An abstract example would be the following to ensure correct resource
55 management::
Georg Brandl116aa622007-08-15 14:28:22 +000056
Georg Brandl116aa622007-08-15 14:28:22 +000057 from contextlib import contextmanager
58
59 @contextmanager
Matthias Bussonnierbde782b2018-07-23 14:10:56 -070060 def managed_resource(*args, **kwds):
61 # Code to acquire resource, e.g.:
62 resource = acquire_resource(*args, **kwds)
63 try:
64 yield resource
65 finally:
66 # Code to release resource, e.g.:
67 release_resource(resource)
Georg Brandl116aa622007-08-15 14:28:22 +000068
Matthias Bussonnierbde782b2018-07-23 14:10:56 -070069 >>> with managed_resource(timeout=3600) as resource:
70 ... # Resource is released at the end of this block,
71 ... # even if code in the block raises an exception
Georg Brandl116aa622007-08-15 14:28:22 +000072
Georg Brandl9afde1c2007-11-01 20:32:30 +000073 The function being decorated must return a :term:`generator`-iterator when
74 called. This iterator must yield exactly one value, which will be bound to
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020075 the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any.
Georg Brandl116aa622007-08-15 14:28:22 +000076
77 At the point where the generator yields, the block nested in the :keyword:`with`
78 statement is executed. The generator is then resumed after the block is exited.
79 If an unhandled exception occurs in the block, it is reraised inside the
80 generator at the point where the yield occurred. Thus, you can use a
81 :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap
82 the error (if any), or ensure that some cleanup takes place. If an exception is
83 trapped merely in order to log it or to perform some action (rather than to
84 suppress it entirely), the generator must reraise that exception. Otherwise the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020085 generator context manager will indicate to the :keyword:`!with` statement that
Georg Brandl116aa622007-08-15 14:28:22 +000086 the exception has been handled, and execution will resume with the statement
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020087 immediately following the :keyword:`!with` statement.
Georg Brandl116aa622007-08-15 14:28:22 +000088
Nick Coghlan0ded3e32011-05-05 23:49:25 +100089 :func:`contextmanager` uses :class:`ContextDecorator` so the context managers
90 it creates can be used as decorators as well as in :keyword:`with` statements.
91 When used as a decorator, a new generator instance is implicitly created on
92 each function call (this allows the otherwise "one-shot" context managers
93 created by :func:`contextmanager` to meet the requirement that context
94 managers support multiple invocations in order to be used as decorators).
Michael Foordb3a89842010-06-30 12:17:50 +000095
96 .. versionchanged:: 3.2
97 Use of :class:`ContextDecorator`.
Georg Brandl116aa622007-08-15 14:28:22 +000098
Georg Brandl86e78d12010-07-18 13:43:32 +000099
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700100.. decorator:: asynccontextmanager
101
102 Similar to :func:`~contextlib.contextmanager`, but creates an
103 :ref:`asynchronous context manager <async-context-managers>`.
104
105 This function is a :term:`decorator` that can be used to define a factory
106 function for :keyword:`async with` statement asynchronous context managers,
107 without needing to create a class or separate :meth:`__aenter__` and
108 :meth:`__aexit__` methods. It must be applied to an :term:`asynchronous
109 generator` function.
110
111 A simple example::
112
113 from contextlib import asynccontextmanager
114
115 @asynccontextmanager
116 async def get_connection():
117 conn = await acquire_db_connection()
118 try:
Alexander Vasin416cbce2018-08-25 05:38:11 +0300119 yield conn
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700120 finally:
121 await release_db_connection(conn)
122
123 async def get_all_users():
124 async with get_connection() as conn:
125 return conn.query('SELECT ...')
126
127 .. versionadded:: 3.7
128
Kazantcev Andrey178695b2020-11-05 11:52:24 +0300129 Context managers defined with :func:`asynccontextmanager` can be used
130 either as decorators or with :keyword:`async with` statements::
131
132 import time
133
134 async def timeit():
135 now = time.monotonic()
136 try:
137 yield
138 finally:
139 print(f'it took {time.monotonic() - now}s to run')
140
141 @timeit()
142 async def main():
143 # ... async code ...
144
145 When used as a decorator, a new generator instance is implicitly created on
146 each function call. This allows the otherwise "one-shot" context managers
147 created by :func:`asynccontextmanager` to meet the requirement that context
148 managers support multiple invocations in order to be used as decorators.
149
150 .. versionchanged:: 3.10
151 Async context managers created with :func:`asynccontextmanager` can
152 be used as decorators.
153
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700154
Georg Brandl116aa622007-08-15 14:28:22 +0000155.. function:: closing(thing)
156
157 Return a context manager that closes *thing* upon completion of the block. This
158 is basically equivalent to::
159
160 from contextlib import contextmanager
161
162 @contextmanager
163 def closing(thing):
164 try:
165 yield thing
166 finally:
167 thing.close()
168
169 And lets you write code like this::
170
Georg Brandl116aa622007-08-15 14:28:22 +0000171 from contextlib import closing
Georg Brandl0f7ede42008-06-23 11:23:31 +0000172 from urllib.request import urlopen
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Miss Islington (bot)f7f1c262021-07-30 07:25:28 -0700174 with closing(urlopen('https://www.python.org')) as page:
Georg Brandl116aa622007-08-15 14:28:22 +0000175 for line in page:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000176 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178 without needing to explicitly close ``page``. Even if an error occurs,
179 ``page.close()`` will be called when the :keyword:`with` block is exited.
180
Georg Brandla7c17e52013-10-13 22:25:10 +0200181
Joongi Kim6e8dcda2020-11-02 17:02:48 +0900182.. class:: aclosing(thing)
183
184 Return an async context manager that calls the ``aclose()`` method of *thing*
185 upon completion of the block. This is basically equivalent to::
186
187 from contextlib import asynccontextmanager
188
189 @asynccontextmanager
190 async def aclosing(thing):
191 try:
192 yield thing
193 finally:
194 await thing.aclose()
195
196 Significantly, ``aclosing()`` supports deterministic cleanup of async
197 generators when they happen to exit early by :keyword:`break` or an
198 exception. For example::
199
200 from contextlib import aclosing
201
202 async with aclosing(my_generator()) as values:
203 async for value in values:
204 if value == 42:
205 break
206
207 This pattern ensures that the generator's async exit code is executed in
208 the same context as its iterations (so that exceptions and context
209 variables work as expected, and the exit code isn't run after the
210 lifetime of some task it depends on).
211
212 .. versionadded:: 3.10
213
214
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100215.. _simplifying-support-for-single-optional-context-managers:
216
217.. function:: nullcontext(enter_result=None)
218
Daniel Porteousc2875452018-07-09 06:49:29 -0700219 Return a context manager that returns *enter_result* from ``__enter__``, but
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100220 otherwise does nothing. It is intended to be used as a stand-in for an
221 optional context manager, for example::
222
Daniel Porteousc2875452018-07-09 06:49:29 -0700223 def myfunction(arg, ignore_exceptions=False):
224 if ignore_exceptions:
225 # Use suppress to ignore all exceptions.
226 cm = contextlib.suppress(Exception)
227 else:
228 # Do not ignore any exceptions, cm has no effect.
229 cm = contextlib.nullcontext()
230 with cm:
231 # Do something
232
233 An example using *enter_result*::
234
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100235 def process_file(file_or_path):
236 if isinstance(file_or_path, str):
237 # If string, open file
238 cm = open(file_or_path)
239 else:
240 # Caller is responsible for closing file
241 cm = nullcontext(file_or_path)
242
243 with cm as file:
244 # Perform processing on the file
245
Tom Gringauza1171672020-11-09 14:34:07 +0200246 It can also be used as a stand-in for
247 :ref:`asynchronous context managers <async-context-managers>`::
248
249 async def send_http(session=None):
250 if not session:
251 # If no http session, create it with aiohttp
252 cm = aiohttp.ClientSession()
253 else:
254 # Caller is responsible for closing the session
255 cm = nullcontext(session)
256
257 async with cm as session:
258 # Send http requests with session
259
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100260 .. versionadded:: 3.7
261
Tom Gringauza1171672020-11-09 14:34:07 +0200262 .. versionchanged:: 3.10
263 :term:`asynchronous context manager` support was added.
264
265
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100266
Nick Coghlan240f86d2013-10-17 23:40:57 +1000267.. function:: suppress(*exceptions)
Raymond Hettingere318a882013-03-10 22:26:51 -0700268
Nick Coghlan240f86d2013-10-17 23:40:57 +1000269 Return a context manager that suppresses any of the specified exceptions
Miss Islington (bot)1065ba62021-06-04 15:10:07 -0700270 if they occur in the body of a :keyword:`!with` statement and then
Irit Katriel6563ea52021-06-01 22:58:06 +0100271 resumes execution with the first statement following the end of the
272 :keyword:`!with` statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700273
Nick Coghlan240f86d2013-10-17 23:40:57 +1000274 As with any other mechanism that completely suppresses exceptions, this
275 context manager should be used only to cover very specific errors where
276 silently continuing with program execution is known to be the right
277 thing to do.
Nick Coghlanb4534ae2013-10-13 23:23:08 +1000278
Raymond Hettingere318a882013-03-10 22:26:51 -0700279 For example::
280
Nick Coghlan240f86d2013-10-17 23:40:57 +1000281 from contextlib import suppress
Raymond Hettingere318a882013-03-10 22:26:51 -0700282
Nick Coghlan240f86d2013-10-17 23:40:57 +1000283 with suppress(FileNotFoundError):
Raymond Hettingere318a882013-03-10 22:26:51 -0700284 os.remove('somefile.tmp')
285
Nick Coghlan240f86d2013-10-17 23:40:57 +1000286 with suppress(FileNotFoundError):
287 os.remove('someotherfile.tmp')
288
Raymond Hettingere318a882013-03-10 22:26:51 -0700289 This code is equivalent to::
290
291 try:
292 os.remove('somefile.tmp')
Nick Coghlanb4534ae2013-10-13 23:23:08 +1000293 except FileNotFoundError:
Raymond Hettingere318a882013-03-10 22:26:51 -0700294 pass
295
Nick Coghlan240f86d2013-10-17 23:40:57 +1000296 try:
297 os.remove('someotherfile.tmp')
298 except FileNotFoundError:
299 pass
300
Nick Coghlan8608d262013-10-20 00:30:51 +1000301 This context manager is :ref:`reentrant <reentrant-cms>`.
302
Raymond Hettingere318a882013-03-10 22:26:51 -0700303 .. versionadded:: 3.4
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Nick Coghlanb4534ae2013-10-13 23:23:08 +1000305
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700306.. function:: redirect_stdout(new_target)
307
308 Context manager for temporarily redirecting :data:`sys.stdout` to
309 another file or file-like object.
310
311 This tool adds flexibility to existing functions or classes whose output
312 is hardwired to stdout.
313
314 For example, the output of :func:`help` normally is sent to *sys.stdout*.
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200315 You can capture that output in a string by redirecting the output to an
Miss Islington (bot)12619412021-05-26 07:34:22 -0700316 :class:`io.StringIO` object. The replacement stream is returned from the
317 ``__enter__`` method and so is available as the target of the
318 :keyword:`with` statement::
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700319
Miss Islington (bot)12619412021-05-26 07:34:22 -0700320 with redirect_stdout(io.StringIO()) as f:
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700321 help(pow)
322 s = f.getvalue()
323
324 To send the output of :func:`help` to a file on disk, redirect the output
325 to a regular file::
326
327 with open('help.txt', 'w') as f:
328 with redirect_stdout(f):
329 help(pow)
330
331 To send the output of :func:`help` to *sys.stderr*::
332
333 with redirect_stdout(sys.stderr):
334 help(pow)
335
Nick Coghlanb4534ae2013-10-13 23:23:08 +1000336 Note that the global side effect on :data:`sys.stdout` means that this
337 context manager is not suitable for use in library code and most threaded
338 applications. It also has no effect on the output of subprocesses.
339 However, it is still a useful approach for many utility scripts.
340
Nick Coghlan36d8ef92014-10-12 10:25:00 +1000341 This context manager is :ref:`reentrant <reentrant-cms>`.
Nick Coghlan8608d262013-10-20 00:30:51 +1000342
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700343 .. versionadded:: 3.4
344
Georg Brandla7c17e52013-10-13 22:25:10 +0200345
Berker Peksagbb44fe02014-11-28 23:28:06 +0200346.. function:: redirect_stderr(new_target)
347
348 Similar to :func:`~contextlib.redirect_stdout` but redirecting
349 :data:`sys.stderr` to another file or file-like object.
350
351 This context manager is :ref:`reentrant <reentrant-cms>`.
352
353 .. versionadded:: 3.5
354
355
Michael Foordb3a89842010-06-30 12:17:50 +0000356.. class:: ContextDecorator()
357
358 A base class that enables a context manager to also be used as a decorator.
359
360 Context managers inheriting from ``ContextDecorator`` have to implement
361 ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional
362 exception handling even when used as a decorator.
363
Georg Brandl86e78d12010-07-18 13:43:32 +0000364 ``ContextDecorator`` is used by :func:`contextmanager`, so you get this
365 functionality automatically.
366
367 Example of ``ContextDecorator``::
Michael Foordb3a89842010-06-30 12:17:50 +0000368
369 from contextlib import ContextDecorator
370
371 class mycontext(ContextDecorator):
Georg Brandl86e78d12010-07-18 13:43:32 +0000372 def __enter__(self):
373 print('Starting')
374 return self
Michael Foordb3a89842010-06-30 12:17:50 +0000375
Georg Brandl86e78d12010-07-18 13:43:32 +0000376 def __exit__(self, *exc):
377 print('Finishing')
378 return False
Michael Foordb3a89842010-06-30 12:17:50 +0000379
380 >>> @mycontext()
381 ... def function():
Georg Brandl86e78d12010-07-18 13:43:32 +0000382 ... print('The bit in the middle')
Michael Foordb3a89842010-06-30 12:17:50 +0000383 ...
384 >>> function()
385 Starting
386 The bit in the middle
387 Finishing
388
389 >>> with mycontext():
Georg Brandl86e78d12010-07-18 13:43:32 +0000390 ... print('The bit in the middle')
Michael Foordb3a89842010-06-30 12:17:50 +0000391 ...
392 Starting
393 The bit in the middle
394 Finishing
395
Georg Brandl86e78d12010-07-18 13:43:32 +0000396 This change is just syntactic sugar for any construct of the following form::
397
398 def f():
399 with cm():
400 # Do stuff
401
402 ``ContextDecorator`` lets you instead write::
403
404 @cm()
405 def f():
406 # Do stuff
407
408 It makes it clear that the ``cm`` applies to the whole function, rather than
409 just a piece of it (and saving an indentation level is nice, too).
410
Michael Foordb3a89842010-06-30 12:17:50 +0000411 Existing context managers that already have a base class can be extended by
412 using ``ContextDecorator`` as a mixin class::
413
414 from contextlib import ContextDecorator
415
416 class mycontext(ContextBaseClass, ContextDecorator):
Georg Brandl86e78d12010-07-18 13:43:32 +0000417 def __enter__(self):
418 return self
Michael Foordb3a89842010-06-30 12:17:50 +0000419
Georg Brandl86e78d12010-07-18 13:43:32 +0000420 def __exit__(self, *exc):
421 return False
Michael Foordb3a89842010-06-30 12:17:50 +0000422
Nick Coghlan0ded3e32011-05-05 23:49:25 +1000423 .. note::
424 As the decorated function must be able to be called multiple times, the
425 underlying context manager must support use in multiple :keyword:`with`
426 statements. If this is not the case, then the original construct with the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200427 explicit :keyword:`!with` statement inside the function should be used.
Nick Coghlan0ded3e32011-05-05 23:49:25 +1000428
Michael Foordb3a89842010-06-30 12:17:50 +0000429 .. versionadded:: 3.2
430
431
kj133aa2d2020-11-06 00:16:27 +0800432.. class:: AsyncContextDecorator
Kazantcev Andrey178695b2020-11-05 11:52:24 +0300433
kj133aa2d2020-11-06 00:16:27 +0800434 Similar to :class:`ContextDecorator` but only for asynchronous functions.
Kazantcev Andrey178695b2020-11-05 11:52:24 +0300435
kj133aa2d2020-11-06 00:16:27 +0800436 Example of ``AsyncContextDecorator``::
Kazantcev Andrey178695b2020-11-05 11:52:24 +0300437
438 from asyncio import run
439 from contextlib import AsyncContextDecorator
440
441 class mycontext(AsyncContextDecorator):
442 async def __aenter__(self):
443 print('Starting')
444 return self
445
446 async def __aexit__(self, *exc):
447 print('Finishing')
448 return False
449
450 >>> @mycontext()
451 ... async def function():
452 ... print('The bit in the middle')
453 ...
454 >>> run(function())
455 Starting
456 The bit in the middle
457 Finishing
458
459 >>> async def function():
460 ... async with mycontext():
461 ... print('The bit in the middle')
462 ...
463 >>> run(function())
464 Starting
465 The bit in the middle
466 Finishing
467
kj133aa2d2020-11-06 00:16:27 +0800468 .. versionadded:: 3.10
469
Kazantcev Andrey178695b2020-11-05 11:52:24 +0300470
Nick Coghlan3267a302012-05-21 22:54:43 +1000471.. class:: ExitStack()
472
473 A context manager that is designed to make it easy to programmatically
474 combine other context managers and cleanup functions, especially those
475 that are optional or otherwise driven by input data.
476
477 For example, a set of files may easily be handled in a single with
478 statement as follows::
479
480 with ExitStack() as stack:
481 files = [stack.enter_context(open(fname)) for fname in filenames]
482 # All opened files will automatically be closed at the end of
483 # the with statement, even if attempts to open files later
Andrew Svetlov5b898402012-12-18 21:26:36 +0200484 # in the list raise an exception
Nick Coghlan3267a302012-05-21 22:54:43 +1000485
486 Each instance maintains a stack of registered callbacks that are called in
487 reverse order when the instance is closed (either explicitly or implicitly
Nick Coghlan27228272012-05-31 22:17:08 +1000488 at the end of a :keyword:`with` statement). Note that callbacks are *not*
489 invoked implicitly when the context stack instance is garbage collected.
Nick Coghlan3267a302012-05-21 22:54:43 +1000490
491 This stack model is used so that context managers that acquire their
492 resources in their ``__init__`` method (such as file objects) can be
493 handled correctly.
494
495 Since registered callbacks are invoked in the reverse order of
Nick Coghlan27228272012-05-31 22:17:08 +1000496 registration, this ends up behaving as if multiple nested :keyword:`with`
Nick Coghlan3267a302012-05-21 22:54:43 +1000497 statements had been used with the registered set of callbacks. This even
498 extends to exception handling - if an inner callback suppresses or replaces
499 an exception, then outer callbacks will be passed arguments based on that
500 updated state.
501
502 This is a relatively low level API that takes care of the details of
503 correctly unwinding the stack of exit callbacks. It provides a suitable
504 foundation for higher level context managers that manipulate the exit
505 stack in application specific ways.
506
Nick Coghlana497b442012-05-22 23:02:00 +1000507 .. versionadded:: 3.3
508
Nick Coghlan3267a302012-05-21 22:54:43 +1000509 .. method:: enter_context(cm)
510
511 Enters a new context manager and adds its :meth:`__exit__` method to
512 the callback stack. The return value is the result of the context
513 manager's own :meth:`__enter__` method.
514
515 These context managers may suppress exceptions just as they normally
Nick Coghlan27228272012-05-31 22:17:08 +1000516 would if used directly as part of a :keyword:`with` statement.
Nick Coghlan3267a302012-05-21 22:54:43 +1000517
518 .. method:: push(exit)
519
520 Adds a context manager's :meth:`__exit__` method to the callback stack.
521
522 As ``__enter__`` is *not* invoked, this method can be used to cover
523 part of an :meth:`__enter__` implementation with a context manager's own
524 :meth:`__exit__` method.
525
526 If passed an object that is not a context manager, this method assumes
527 it is a callback with the same signature as a context manager's
528 :meth:`__exit__` method and adds it directly to the callback stack.
529
530 By returning true values, these callbacks can suppress exceptions the
531 same way context manager :meth:`__exit__` methods can.
532
533 The passed in object is returned from the function, allowing this
Nick Coghlan27228272012-05-31 22:17:08 +1000534 method to be used as a function decorator.
Nick Coghlan3267a302012-05-21 22:54:43 +1000535
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300536 .. method:: callback(callback, /, *args, **kwds)
Nick Coghlan3267a302012-05-21 22:54:43 +1000537
538 Accepts an arbitrary callback function and arguments and adds it to
539 the callback stack.
540
541 Unlike the other methods, callbacks added this way cannot suppress
542 exceptions (as they are never passed the exception details).
543
544 The passed in callback is returned from the function, allowing this
Nick Coghlan27228272012-05-31 22:17:08 +1000545 method to be used as a function decorator.
Nick Coghlan3267a302012-05-21 22:54:43 +1000546
547 .. method:: pop_all()
548
549 Transfers the callback stack to a fresh :class:`ExitStack` instance
550 and returns it. No callbacks are invoked by this operation - instead,
551 they will now be invoked when the new stack is closed (either
Nick Coghlan27228272012-05-31 22:17:08 +1000552 explicitly or implicitly at the end of a :keyword:`with` statement).
Nick Coghlan3267a302012-05-21 22:54:43 +1000553
554 For example, a group of files can be opened as an "all or nothing"
555 operation as follows::
556
557 with ExitStack() as stack:
558 files = [stack.enter_context(open(fname)) for fname in filenames]
Barry Warsawd8f870d2013-05-10 11:35:38 -0400559 # Hold onto the close method, but don't call it yet.
560 close_files = stack.pop_all().close
Nick Coghlan3267a302012-05-21 22:54:43 +1000561 # If opening any file fails, all previously opened files will be
562 # closed automatically. If all files are opened successfully,
563 # they will remain open even after the with statement ends.
Barry Warsawd8f870d2013-05-10 11:35:38 -0400564 # close_files() can then be invoked explicitly to close them all.
Nick Coghlan3267a302012-05-21 22:54:43 +1000565
566 .. method:: close()
567
568 Immediately unwinds the callback stack, invoking callbacks in the
569 reverse order of registration. For any context managers and exit
570 callbacks registered, the arguments passed in will indicate that no
571 exception occurred.
572
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800573.. class:: AsyncExitStack()
574
575 An :ref:`asynchronous context manager <async-context-managers>`, similar
576 to :class:`ExitStack`, that supports combining both synchronous and
577 asynchronous context managers, as well as having coroutines for
578 cleanup logic.
579
580 The :meth:`close` method is not implemented, :meth:`aclose` must be used
581 instead.
582
Miss Islington (bot)65dede62021-05-19 13:37:32 -0700583 .. coroutinemethod:: enter_async_context(cm)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800584
585 Similar to :meth:`enter_context` but expects an asynchronous context
586 manager.
587
588 .. method:: push_async_exit(exit)
589
590 Similar to :meth:`push` but expects either an asynchronous context manager
Nathaniel J. Smitha3c88ef2018-09-18 14:27:59 -0700591 or a coroutine function.
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800592
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300593 .. method:: push_async_callback(callback, /, *args, **kwds)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800594
Nathaniel J. Smitha3c88ef2018-09-18 14:27:59 -0700595 Similar to :meth:`callback` but expects a coroutine function.
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800596
Miss Islington (bot)65dede62021-05-19 13:37:32 -0700597 .. coroutinemethod:: aclose()
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800598
599 Similar to :meth:`close` but properly handles awaitables.
600
601 Continuing the example for :func:`asynccontextmanager`::
602
603 async with AsyncExitStack() as stack:
604 connections = [await stack.enter_async_context(get_connection())
605 for i in range(5)]
606 # All opened connections will automatically be released at the end of
607 # the async with statement, even if attempts to open a connection
608 # later in the list raise an exception.
609
610 .. versionadded:: 3.7
Nick Coghlan3267a302012-05-21 22:54:43 +1000611
612Examples and Recipes
613--------------------
614
615This section describes some examples and recipes for making effective use of
616the tools provided by :mod:`contextlib`.
617
618
Nick Coghlan27228272012-05-31 22:17:08 +1000619Supporting a variable number of context managers
620^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
621
622The primary use case for :class:`ExitStack` is the one given in the class
623documentation: supporting a variable number of context managers and other
624cleanup operations in a single :keyword:`with` statement. The variability
625may come from the number of context managers needed being driven by user
626input (such as opening a user specified collection of files), or from
627some of the context managers being optional::
628
629 with ExitStack() as stack:
630 for resource in resources:
631 stack.enter_context(resource)
Raymond Hettingere8e2df32014-05-25 18:06:04 -0700632 if need_special_resource():
Nick Coghlan27228272012-05-31 22:17:08 +1000633 special = acquire_special_resource()
634 stack.callback(release_special_resource, special)
635 # Perform operations that use the acquired resources
636
637As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with`
638statements to manage arbitrary resources that don't natively support the
639context management protocol.
640
641
Nick Coghlan27228272012-05-31 22:17:08 +1000642Catching exceptions from ``__enter__`` methods
643^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
644
645It is occasionally desirable to catch exceptions from an ``__enter__``
646method implementation, *without* inadvertently catching exceptions from
647the :keyword:`with` statement body or the context manager's ``__exit__``
648method. By using :class:`ExitStack` the steps in the context management
649protocol can be separated slightly in order to allow this::
650
651 stack = ExitStack()
652 try:
653 x = stack.enter_context(cm)
654 except Exception:
655 # handle __enter__ exception
656 else:
657 with stack:
658 # Handle normal case
659
660Actually needing to do this is likely to indicate that the underlying API
661should be providing a direct resource management interface for use with
662:keyword:`try`/:keyword:`except`/:keyword:`finally` statements, but not
663all APIs are well designed in that regard. When a context manager is the
664only resource management API provided, then :class:`ExitStack` can make it
665easier to handle various situations that can't be handled directly in a
666:keyword:`with` statement.
667
668
Nick Coghlan3267a302012-05-21 22:54:43 +1000669Cleaning up in an ``__enter__`` implementation
670^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
671
672As noted in the documentation of :meth:`ExitStack.push`, this
673method can be useful in cleaning up an already allocated resource if later
674steps in the :meth:`__enter__` implementation fail.
675
676Here's an example of doing this for a context manager that accepts resource
677acquisition and release functions, along with an optional validation function,
678and maps them to the context management protocol::
679
Brett Cannon9e080e02016-04-08 12:15:27 -0700680 from contextlib import contextmanager, AbstractContextManager, ExitStack
Nick Coghlan3267a302012-05-21 22:54:43 +1000681
Brett Cannon9e080e02016-04-08 12:15:27 -0700682 class ResourceManager(AbstractContextManager):
Nick Coghlan3267a302012-05-21 22:54:43 +1000683
684 def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
685 self.acquire_resource = acquire_resource
686 self.release_resource = release_resource
687 if check_resource_ok is None:
688 def check_resource_ok(resource):
689 return True
690 self.check_resource_ok = check_resource_ok
691
692 @contextmanager
693 def _cleanup_on_error(self):
694 with ExitStack() as stack:
695 stack.push(self)
696 yield
697 # The validation check passed and didn't raise an exception
698 # Accordingly, we want to keep the resource, and pass it
699 # back to our caller
700 stack.pop_all()
701
702 def __enter__(self):
703 resource = self.acquire_resource()
704 with self._cleanup_on_error():
705 if not self.check_resource_ok(resource):
706 msg = "Failed validation for {!r}"
707 raise RuntimeError(msg.format(resource))
708 return resource
709
710 def __exit__(self, *exc_details):
711 # We don't need to duplicate any of our resource release logic
712 self.release_resource()
713
714
715Replacing any use of ``try-finally`` and flag variables
716^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
717
718A pattern you will sometimes see is a ``try-finally`` statement with a flag
719variable to indicate whether or not the body of the ``finally`` clause should
720be executed. In its simplest form (that can't already be handled just by
721using an ``except`` clause instead), it looks something like this::
722
723 cleanup_needed = True
724 try:
725 result = perform_operation()
726 if result:
727 cleanup_needed = False
728 finally:
729 if cleanup_needed:
730 cleanup_resources()
731
732As with any ``try`` statement based code, this can cause problems for
733development and review, because the setup code and the cleanup code can end
734up being separated by arbitrarily long sections of code.
735
736:class:`ExitStack` makes it possible to instead register a callback for
737execution at the end of a ``with`` statement, and then later decide to skip
738executing that callback::
739
740 from contextlib import ExitStack
741
742 with ExitStack() as stack:
743 stack.callback(cleanup_resources)
744 result = perform_operation()
745 if result:
746 stack.pop_all()
747
748This allows the intended cleanup up behaviour to be made explicit up front,
749rather than requiring a separate flag variable.
750
751If a particular application uses this pattern a lot, it can be simplified
752even further by means of a small helper class::
753
754 from contextlib import ExitStack
755
756 class Callback(ExitStack):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300757 def __init__(self, callback, /, *args, **kwds):
Andre Delfino52cd6d52021-04-26 19:13:54 -0300758 super().__init__()
Nick Coghlan3267a302012-05-21 22:54:43 +1000759 self.callback(callback, *args, **kwds)
760
761 def cancel(self):
762 self.pop_all()
763
764 with Callback(cleanup_resources) as cb:
765 result = perform_operation()
766 if result:
767 cb.cancel()
768
769If the resource cleanup isn't already neatly bundled into a standalone
770function, then it is still possible to use the decorator form of
771:meth:`ExitStack.callback` to declare the resource cleanup in
772advance::
773
774 from contextlib import ExitStack
775
776 with ExitStack() as stack:
777 @stack.callback
778 def cleanup_resources():
779 ...
780 result = perform_operation()
781 if result:
782 stack.pop_all()
783
784Due to the way the decorator protocol works, a callback function
785declared this way cannot take any parameters. Instead, any resources to
Martin Panterd21e0b52015-10-10 10:36:22 +0000786be released must be accessed as closure variables.
Nick Coghlan3267a302012-05-21 22:54:43 +1000787
788
789Using a context manager as a function decorator
790^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
791
792:class:`ContextDecorator` makes it possible to use a context manager in
793both an ordinary ``with`` statement and also as a function decorator.
794
795For example, it is sometimes useful to wrap functions or groups of statements
796with a logger that can track the time of entry and time of exit. Rather than
797writing both a function decorator and a context manager for the task,
798inheriting from :class:`ContextDecorator` provides both capabilities in a
799single definition::
800
801 from contextlib import ContextDecorator
802 import logging
803
804 logging.basicConfig(level=logging.INFO)
805
806 class track_entry_and_exit(ContextDecorator):
807 def __init__(self, name):
808 self.name = name
809
810 def __enter__(self):
Vinay Sajipdd917f82016-08-31 08:22:29 +0100811 logging.info('Entering: %s', self.name)
Nick Coghlan3267a302012-05-21 22:54:43 +1000812
813 def __exit__(self, exc_type, exc, exc_tb):
Vinay Sajipdd917f82016-08-31 08:22:29 +0100814 logging.info('Exiting: %s', self.name)
Nick Coghlan3267a302012-05-21 22:54:43 +1000815
816Instances of this class can be used as both a context manager::
817
818 with track_entry_and_exit('widget loader'):
819 print('Some time consuming activity goes here')
820 load_widget()
821
822And also as a function decorator::
823
824 @track_entry_and_exit('widget loader')
825 def activity():
826 print('Some time consuming activity goes here')
827 load_widget()
828
829Note that there is one additional limitation when using context managers
830as function decorators: there's no way to access the return value of
831:meth:`__enter__`. If that value is needed, then it is still necessary to use
832an explicit ``with`` statement.
833
Georg Brandl116aa622007-08-15 14:28:22 +0000834.. seealso::
835
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300836 :pep:`343` - The "with" statement
Georg Brandl116aa622007-08-15 14:28:22 +0000837 The specification, background, and examples for the Python :keyword:`with`
838 statement.
839
Nick Coghlan0acceb72013-10-20 13:22:21 +1000840.. _single-use-reusable-and-reentrant-cms:
Nick Coghlan8608d262013-10-20 00:30:51 +1000841
Nick Coghlan0acceb72013-10-20 13:22:21 +1000842Single use, reusable and reentrant context managers
843---------------------------------------------------
Nick Coghlan8608d262013-10-20 00:30:51 +1000844
845Most context managers are written in a way that means they can only be
846used effectively in a :keyword:`with` statement once. These single use
847context managers must be created afresh each time they're used -
848attempting to use them a second time will trigger an exception or
849otherwise not work correctly.
850
851This common limitation means that it is generally advisable to create
852context managers directly in the header of the :keyword:`with` statement
853where they are used (as shown in all of the usage examples above).
854
855Files are an example of effectively single use context managers, since
856the first :keyword:`with` statement will close the file, preventing any
857further IO operations using that file object.
858
859Context managers created using :func:`contextmanager` are also single use
860context managers, and will complain about the underlying generator failing
861to yield if an attempt is made to use them a second time::
862
863 >>> from contextlib import contextmanager
864 >>> @contextmanager
865 ... def singleuse():
866 ... print("Before")
867 ... yield
868 ... print("After")
869 ...
870 >>> cm = singleuse()
871 >>> with cm:
872 ... pass
873 ...
874 Before
875 After
876 >>> with cm:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300877 ... pass
Nick Coghlan8608d262013-10-20 00:30:51 +1000878 ...
879 Traceback (most recent call last):
880 ...
881 RuntimeError: generator didn't yield
882
883
884.. _reentrant-cms:
885
886Reentrant context managers
887^^^^^^^^^^^^^^^^^^^^^^^^^^
888
889More sophisticated context managers may be "reentrant". These context
890managers can not only be used in multiple :keyword:`with` statements,
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200891but may also be used *inside* a :keyword:`!with` statement that is already
Nick Coghlan8608d262013-10-20 00:30:51 +1000892using the same context manager.
893
Nick Coghlan8e113b42013-11-03 17:00:51 +1000894:class:`threading.RLock` is an example of a reentrant context manager, as are
895:func:`suppress` and :func:`redirect_stdout`. Here's a very simple example of
896reentrant use::
Nick Coghlan8608d262013-10-20 00:30:51 +1000897
Nick Coghlan8e113b42013-11-03 17:00:51 +1000898 >>> from contextlib import redirect_stdout
899 >>> from io import StringIO
900 >>> stream = StringIO()
901 >>> write_to_stream = redirect_stdout(stream)
902 >>> with write_to_stream:
903 ... print("This is written to the stream rather than stdout")
904 ... with write_to_stream:
905 ... print("This is also written to the stream")
Nick Coghlan8608d262013-10-20 00:30:51 +1000906 ...
Nick Coghlan8e113b42013-11-03 17:00:51 +1000907 >>> print("This is written directly to stdout")
908 This is written directly to stdout
909 >>> print(stream.getvalue())
910 This is written to the stream rather than stdout
911 This is also written to the stream
912
913Real world examples of reentrancy are more likely to involve multiple
914functions calling each other and hence be far more complicated than this
915example.
916
917Note also that being reentrant is *not* the same thing as being thread safe.
918:func:`redirect_stdout`, for example, is definitely not thread safe, as it
919makes a global modification to the system state by binding :data:`sys.stdout`
920to a different stream.
Nick Coghlan8608d262013-10-20 00:30:51 +1000921
922
923.. _reusable-cms:
924
925Reusable context managers
926^^^^^^^^^^^^^^^^^^^^^^^^^
927
928Distinct from both single use and reentrant context managers are "reusable"
929context managers (or, to be completely explicit, "reusable, but not
930reentrant" context managers, since reentrant context managers are also
931reusable). These context managers support being used multiple times, but
932will fail (or otherwise not work correctly) if the specific context manager
933instance has already been used in a containing with statement.
934
Nick Coghlan8e113b42013-11-03 17:00:51 +1000935:class:`threading.Lock` is an example of a reusable, but not reentrant,
936context manager (for a reentrant lock, it is necessary to use
937:class:`threading.RLock` instead).
Nick Coghlan8608d262013-10-20 00:30:51 +1000938
Nick Coghlan8e113b42013-11-03 17:00:51 +1000939Another example of a reusable, but not reentrant, context manager is
940:class:`ExitStack`, as it invokes *all* currently registered callbacks
941when leaving any with statement, regardless of where those callbacks
942were added::
Nick Coghlan8608d262013-10-20 00:30:51 +1000943
Nick Coghlan8e113b42013-11-03 17:00:51 +1000944 >>> from contextlib import ExitStack
945 >>> stack = ExitStack()
946 >>> with stack:
947 ... stack.callback(print, "Callback: from first context")
948 ... print("Leaving first context")
Nick Coghlan8608d262013-10-20 00:30:51 +1000949 ...
Nick Coghlan8e113b42013-11-03 17:00:51 +1000950 Leaving first context
951 Callback: from first context
952 >>> with stack:
953 ... stack.callback(print, "Callback: from second context")
954 ... print("Leaving second context")
955 ...
956 Leaving second context
957 Callback: from second context
958 >>> with stack:
959 ... stack.callback(print, "Callback: from outer context")
960 ... with stack:
961 ... stack.callback(print, "Callback: from inner context")
962 ... print("Leaving inner context")
963 ... print("Leaving outer context")
964 ...
965 Leaving inner context
966 Callback: from inner context
967 Callback: from outer context
968 Leaving outer context
969
970As the output from the example shows, reusing a single stack object across
971multiple with statements works correctly, but attempting to nest them
972will cause the stack to be cleared at the end of the innermost with
973statement, which is unlikely to be desirable behaviour.
974
975Using separate :class:`ExitStack` instances instead of reusing a single
976instance avoids that problem::
977
978 >>> from contextlib import ExitStack
979 >>> with ExitStack() as outer_stack:
980 ... outer_stack.callback(print, "Callback: from outer context")
981 ... with ExitStack() as inner_stack:
982 ... inner_stack.callback(print, "Callback: from inner context")
983 ... print("Leaving inner context")
984 ... print("Leaving outer context")
985 ...
986 Leaving inner context
987 Callback: from inner context
988 Leaving outer context
989 Callback: from outer context