Debian Codegraph @

Doc/library/contextlib.rst

raw
1 :mod:`!contextlib` --- Utilities for :keyword:`!with`\ -statement contexts
2 ==========================================================================
3
4 .. module:: contextlib
5 :synopsis: Utilities for with-statement contexts.
6
7 **Source code:** :source:`Lib/contextlib.py`
8
9 --------------
10
11 This module provides utilities for common tasks involving the :keyword:`with`
12 statement. For more information see also :ref:`typecontextmanager` and
13 :ref:`context-managers`.
14
15
16 Utilities
17 ---------
18
19 Functions and classes provided:
20
21 .. class:: AbstractContextManager
22
23 An :term:`abstract base class` for classes that implement
24 :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
32 .. 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
43
44 .. decorator:: contextmanager
45
46 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:`~object.__enter__` and :meth:`~object.__exit__` methods.
49
50 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::
56
57 from contextlib import contextmanager
58
59 @contextmanager
60 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)
68
69 The function can then be used like this::
70
71 >>> with managed_resource(timeout=3600) as resource:
72 ... # Resource is released at the end of this block,
73 ... # even if code in the block raises an exception
74
75 The function being decorated must return a :term:`generator`-iterator when
76 called. This iterator must yield exactly one value, which will be bound to
77 the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any.
78
79 At the point where the generator yields, the block nested in the :keyword:`with`
80 statement is executed. The generator is then resumed after the block is exited.
81 If an unhandled exception occurs in the block, it is reraised inside the
82 generator at the point where the yield occurred. Thus, you can use a
83 :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap
84 the error (if any), or ensure that some cleanup takes place. If an exception is
85 trapped merely in order to log it or to perform some action (rather than to
86 suppress it entirely), the generator must reraise that exception. Otherwise the
87 generator context manager will indicate to the :keyword:`!with` statement that
88 the exception has been handled, and execution will resume with the statement
89 immediately following the :keyword:`!with` statement.
90
91 :func:`contextmanager` uses :class:`ContextDecorator` so the context managers
92 it creates can be used as decorators as well as in :keyword:`with` statements.
93 When used as a decorator, a new generator instance is implicitly created on
94 each function call (this allows the otherwise "one-shot" context managers
95 created by :func:`contextmanager` to meet the requirement that context
96 managers support multiple invocations in order to be used as decorators).
97
98 .. versionchanged:: 3.2
99 Use of :class:`ContextDecorator`.
100
101
102 .. decorator:: asynccontextmanager
103
104 Similar to :func:`~contextlib.contextmanager`, but creates an
105 :ref:`asynchronous context manager <async-context-managers>`.
106
107 This function is a :term:`decorator` that can be used to define a factory
108 function for :keyword:`async with` statement asynchronous context managers,
109 without needing to create a class or separate :meth:`~object.__aenter__` and
110 :meth:`~object.__aexit__` methods. It must be applied to an :term:`asynchronous
111 generator` function.
112
113 A simple example::
114
115 from contextlib import asynccontextmanager
116
117 @asynccontextmanager
118 async def get_connection():
119 conn = await acquire_db_connection()
120 try:
121 yield conn
122 finally:
123 await release_db_connection(conn)
124
125 async def get_all_users():
126 async with get_connection() as conn:
127 return conn.query('SELECT ...')
128
129 .. versionadded:: 3.7
130
131 Context managers defined with :func:`asynccontextmanager` can be used
132 either as decorators or with :keyword:`async with` statements::
133
134 import time
135 from contextlib import asynccontextmanager
136
137 @asynccontextmanager
138 async def timeit():
139 now = time.monotonic()
140 try:
141 yield
142 finally:
143 print(f'it took {time.monotonic() - now}s to run')
144
145 @timeit()
146 async def main():
147 # ... async code ...
148
149 When used as a decorator, a new generator instance is implicitly created on
150 each function call. This allows the otherwise "one-shot" context managers
151 created by :func:`asynccontextmanager` to meet the requirement that context
152 managers support multiple invocations in order to be used as decorators.
153
154 .. versionchanged:: 3.10
155 Async context managers created with :func:`asynccontextmanager` can
156 be used as decorators.
157
158
159 .. function:: closing(thing)
160
161 Return a context manager that closes *thing* upon completion of the block. This
162 is basically equivalent to::
163
164 from contextlib import contextmanager
165
166 @contextmanager
167 def closing(thing):
168 try:
169 yield thing
170 finally:
171 thing.close()
172
173 And lets you write code like this::
174
175 from contextlib import closing
176 from urllib.request import urlopen
177
178 with closing(urlopen('https://www.python.org')) as page:
179 for line in page:
180 print(line)
181
182 without needing to explicitly close ``page``. Even if an error occurs,
183 ``page.close()`` will be called when the :keyword:`with` block is exited.
184
185 .. note::
186
187 Most types managing resources support the :term:`context manager` protocol,
188 which closes *thing* on leaving the :keyword:`with` statement.
189 As such, :func:`!closing` is most useful for third party types that don't
190 support context managers.
191 This example is purely for illustration purposes,
192 as :func:`~urllib.request.urlopen` would normally be used in a context manager.
193
194 .. function:: aclosing(thing)
195
196 Return an async context manager that calls the ``aclose()`` method of *thing*
197 upon completion of the block. This is basically equivalent to::
198
199 from contextlib import asynccontextmanager
200
201 @asynccontextmanager
202 async def aclosing(thing):
203 try:
204 yield thing
205 finally:
206 await thing.aclose()
207
208 Significantly, ``aclosing()`` supports deterministic cleanup of async
209 generators when they happen to exit early by :keyword:`break` or an
210 exception. For example::
211
212 from contextlib import aclosing
213
214 async with aclosing(my_generator()) as values:
215 async for value in values:
216 if value == 42:
217 break
218
219 This pattern ensures that the generator's async exit code is executed in
220 the same context as its iterations (so that exceptions and context
221 variables work as expected, and the exit code isn't run after the
222 lifetime of some task it depends on).
223
224 .. versionadded:: 3.10
225
226
227 .. _simplifying-support-for-single-optional-context-managers:
228
229 .. function:: nullcontext(enter_result=None)
230
231 Return a context manager that returns *enter_result* from ``__enter__``, but
232 otherwise does nothing. It is intended to be used as a stand-in for an
233 optional context manager, for example::
234
235 def myfunction(arg, ignore_exceptions=False):
236 if ignore_exceptions:
237 # Use suppress to ignore all exceptions.
238 cm = contextlib.suppress(Exception)
239 else:
240 # Do not ignore any exceptions, cm has no effect.
241 cm = contextlib.nullcontext()
242 with cm:
243 # Do something
244
245 An example using *enter_result*::
246
247 def process_file(file_or_path):
248 if isinstance(file_or_path, str):
249 # If string, open file
250 cm = open(file_or_path)
251 else:
252 # Caller is responsible for closing file
253 cm = nullcontext(file_or_path)
254
255 with cm as file:
256 # Perform processing on the file
257
258 It can also be used as a stand-in for
259 :ref:`asynchronous context managers <async-context-managers>`::
260
261 async def send_http(session=None):
262 if not session:
263 # If no http session, create it with aiohttp
264 cm = aiohttp.ClientSession()
265 else:
266 # Caller is responsible for closing the session
267 cm = nullcontext(session)
268
269 async with cm as session:
270 # Send http requests with session
271
272 .. versionadded:: 3.7
273
274 .. versionchanged:: 3.10
275 :term:`asynchronous context manager` support was added.
276
277
278
279 .. function:: suppress(*exceptions)
280
281 Return a context manager that suppresses any of the specified exceptions
282 if they occur in the body of a :keyword:`!with` statement and then
283 resumes execution with the first statement following the end of the
284 :keyword:`!with` statement.
285
286 As with any other mechanism that completely suppresses exceptions, this
287 context manager should be used only to cover very specific errors where
288 silently continuing with program execution is known to be the right
289 thing to do.
290
291 For example::
292
293 from contextlib import suppress
294
295 with suppress(FileNotFoundError):
296 os.remove('somefile.tmp')
297
298 with suppress(FileNotFoundError):
299 os.remove('someotherfile.tmp')
300
301 This code is equivalent to::
302
303 try:
304 os.remove('somefile.tmp')
305 except FileNotFoundError:
306 pass
307
308 try:
309 os.remove('someotherfile.tmp')
310 except FileNotFoundError:
311 pass
312
313 This context manager is :ref:`reentrant <reentrant-cms>`.
314
315 If the code within the :keyword:`!with` block raises a
316 :exc:`BaseExceptionGroup`, suppressed exceptions are removed from the
317 group. Any exceptions of the group which are not suppressed are re-raised in
318 a new group which is created using the original group's :meth:`~BaseExceptionGroup.derive`
319 method.
320
321 .. versionadded:: 3.4
322
323 .. versionchanged:: 3.12
324 ``suppress`` now supports suppressing exceptions raised as
325 part of a :exc:`BaseExceptionGroup`.
326
327 .. function:: redirect_stdout(new_target)
328
329 Context manager for temporarily redirecting :data:`sys.stdout` to
330 another file or file-like object.
331
332 This tool adds flexibility to existing functions or classes whose output
333 is hardwired to stdout.
334
335 For example, the output of :func:`help` normally is sent to *sys.stdout*.
336 You can capture that output in a string by redirecting the output to an
337 :class:`io.StringIO` object. The replacement stream is returned from the
338 ``__enter__`` method and so is available as the target of the
339 :keyword:`with` statement::
340
341 with redirect_stdout(io.StringIO()) as f:
342 help(pow)
343 s = f.getvalue()
344
345 To send the output of :func:`help` to a file on disk, redirect the output
346 to a regular file::
347
348 with open('help.txt', 'w') as f:
349 with redirect_stdout(f):
350 help(pow)
351
352 To send the output of :func:`help` to *sys.stderr*::
353
354 with redirect_stdout(sys.stderr):
355 help(pow)
356
357 Note that the global side effect on :data:`sys.stdout` means that this
358 context manager is not suitable for use in library code and most threaded
359 applications. It also has no effect on the output of subprocesses.
360 However, it is still a useful approach for many utility scripts.
361
362 This context manager is :ref:`reentrant <reentrant-cms>`.
363
364 .. versionadded:: 3.4
365
366
367 .. function:: redirect_stderr(new_target)
368
369 Similar to :func:`~contextlib.redirect_stdout` but redirecting
370 :data:`sys.stderr` to another file or file-like object.
371
372 This context manager is :ref:`reentrant <reentrant-cms>`.
373
374 .. versionadded:: 3.5
375
376
377 .. function:: chdir(path)
378
379 Non parallel-safe context manager to change the current working directory.
380 As this changes a global state, the working directory, it is not suitable
381 for use in most threaded or async contexts. It is also not suitable for most
382 non-linear code execution, like generators, where the program execution is
383 temporarily relinquished -- unless explicitly desired, you should not yield
384 when this context manager is active.
385
386 This is a simple wrapper around :func:`~os.chdir`, it changes the current
387 working directory upon entering and restores the old one on exit.
388
389 This context manager is :ref:`reentrant <reentrant-cms>`.
390
391 .. versionadded:: 3.11
392
393
394 .. class:: ContextDecorator()
395
396 A base class that enables a context manager to also be used as a decorator.
397
398 Context managers inheriting from ``ContextDecorator`` have to implement
399 ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional
400 exception handling even when used as a decorator.
401
402 ``ContextDecorator`` is used by :func:`contextmanager`, so you get this
403 functionality automatically.
404
405 Example of ``ContextDecorator``::
406
407 from contextlib import ContextDecorator
408
409 class mycontext(ContextDecorator):
410 def __enter__(self):
411 print('Starting')
412 return self
413
414 def __exit__(self, *exc):
415 print('Finishing')
416 return False
417
418 The class can then be used like this::
419
420 >>> @mycontext()
421 ... def function():
422 ... print('The bit in the middle')
423 ...
424 >>> function()
425 Starting
426 The bit in the middle
427 Finishing
428
429 >>> with mycontext():
430 ... print('The bit in the middle')
431 ...
432 Starting
433 The bit in the middle
434 Finishing
435
436 This change is just syntactic sugar for any construct of the following form::
437
438 def f():
439 with cm():
440 # Do stuff
441
442 ``ContextDecorator`` lets you instead write::
443
444 @cm()
445 def f():
446 # Do stuff
447
448 It makes it clear that the ``cm`` applies to the whole function, rather than
449 just a piece of it (and saving an indentation level is nice, too).
450
451 Existing context managers that already have a base class can be extended by
452 using ``ContextDecorator`` as a mixin class::
453
454 from contextlib import ContextDecorator
455
456 class mycontext(ContextBaseClass, ContextDecorator):
457 def __enter__(self):
458 return self
459
460 def __exit__(self, *exc):
461 return False
462
463 .. note::
464 As the decorated function must be able to be called multiple times, the
465 underlying context manager must support use in multiple :keyword:`with`
466 statements. If this is not the case, then the original construct with the
467 explicit :keyword:`!with` statement inside the function should be used.
468
469 .. versionadded:: 3.2
470
471
472 .. class:: AsyncContextDecorator
473
474 Similar to :class:`ContextDecorator` but only for asynchronous functions.
475
476 Example of ``AsyncContextDecorator``::
477
478 from asyncio import run
479 from contextlib import AsyncContextDecorator
480
481 class mycontext(AsyncContextDecorator):
482 async def __aenter__(self):
483 print('Starting')
484 return self
485
486 async def __aexit__(self, *exc):
487 print('Finishing')
488 return False
489
490 The class can then be used like this::
491
492 >>> @mycontext()
493 ... async def function():
494 ... print('The bit in the middle')
495 ...
496 >>> run(function())
497 Starting
498 The bit in the middle
499 Finishing
500
501 >>> async def function():
502 ... async with mycontext():
503 ... print('The bit in the middle')
504 ...
505 >>> run(function())
506 Starting
507 The bit in the middle
508 Finishing
509
510 .. versionadded:: 3.10
511
512
513 .. class:: ExitStack()
514
515 A context manager that is designed to make it easy to programmatically
516 combine other context managers and cleanup functions, especially those
517 that are optional or otherwise driven by input data.
518
519 For example, a set of files may easily be handled in a single with
520 statement as follows::
521
522 with ExitStack() as stack:
523 files = [stack.enter_context(open(fname)) for fname in filenames]
524 # All opened files will automatically be closed at the end of
525 # the with statement, even if attempts to open files later
526 # in the list raise an exception
527
528 The :meth:`~object.__enter__` method returns the :class:`ExitStack` instance, and
529 performs no additional operations.
530
531 Each instance maintains a stack of registered callbacks that are called in
532 reverse order when the instance is closed (either explicitly or implicitly
533 at the end of a :keyword:`with` statement). Note that callbacks are *not*
534 invoked implicitly when the context stack instance is garbage collected.
535
536 This stack model is used so that context managers that acquire their
537 resources in their ``__init__`` method (such as file objects) can be
538 handled correctly.
539
540 Since registered callbacks are invoked in the reverse order of
541 registration, this ends up behaving as if multiple nested :keyword:`with`
542 statements had been used with the registered set of callbacks. This even
543 extends to exception handling - if an inner callback suppresses or replaces
544 an exception, then outer callbacks will be passed arguments based on that
545 updated state.
546
547 This is a relatively low level API that takes care of the details of
548 correctly unwinding the stack of exit callbacks. It provides a suitable
549 foundation for higher level context managers that manipulate the exit
550 stack in application specific ways.
551
552 .. versionadded:: 3.3
553
554 .. method:: enter_context(cm)
555
556 Enters a new context manager and adds its :meth:`~object.__exit__` method to
557 the callback stack. The return value is the result of the context
558 manager's own :meth:`~object.__enter__` method.
559
560 These context managers may suppress exceptions just as they normally
561 would if used directly as part of a :keyword:`with` statement.
562
563 .. versionchanged:: 3.11
564 Raises :exc:`TypeError` instead of :exc:`AttributeError` if *cm*
565 is not a context manager.
566
567 .. method:: push(exit)
568
569 Adds a context manager's :meth:`~object.__exit__` method to the callback stack.
570
571 As ``__enter__`` is *not* invoked, this method can be used to cover
572 part of an :meth:`~object.__enter__` implementation with a context manager's own
573 :meth:`~object.__exit__` method.
574
575 If passed an object that is not a context manager, this method assumes
576 it is a callback with the same signature as a context manager's
577 :meth:`~object.__exit__` method and adds it directly to the callback stack.
578
579 By returning true values, these callbacks can suppress exceptions the
580 same way context manager :meth:`~object.__exit__` methods can.
581
582 The passed in object is returned from the function, allowing this
583 method to be used as a function decorator.
584
585 .. method:: callback(callback, /, *args, **kwds)
586
587 Accepts an arbitrary callback function and arguments and adds it to
588 the callback stack.
589
590 Unlike the other methods, callbacks added this way cannot suppress
591 exceptions (as they are never passed the exception details).
592
593 The passed in callback is returned from the function, allowing this
594 method to be used as a function decorator.
595
596 .. method:: pop_all()
597
598 Transfers the callback stack to a fresh :class:`ExitStack` instance
599 and returns it. No callbacks are invoked by this operation - instead,
600 they will now be invoked when the new stack is closed (either
601 explicitly or implicitly at the end of a :keyword:`with` statement).
602
603 For example, a group of files can be opened as an "all or nothing"
604 operation as follows::
605
606 with ExitStack() as stack:
607 files = [stack.enter_context(open(fname)) for fname in filenames]
608 # Hold onto the close method, but don't call it yet.
609 close_files = stack.pop_all().close
610 # If opening any file fails, all previously opened files will be
611 # closed automatically. If all files are opened successfully,
612 # they will remain open even after the with statement ends.
613 # close_files() can then be invoked explicitly to close them all.
614
615 .. method:: close()
616
617 Immediately unwinds the callback stack, invoking callbacks in the
618 reverse order of registration. For any context managers and exit
619 callbacks registered, the arguments passed in will indicate that no
620 exception occurred.
621
622 .. class:: AsyncExitStack()
623
624 An :ref:`asynchronous context manager <async-context-managers>`, similar
625 to :class:`ExitStack`, that supports combining both synchronous and
626 asynchronous context managers, as well as having coroutines for
627 cleanup logic.
628
629 The :meth:`~ExitStack.close` method is not implemented; :meth:`aclose` must be used
630 instead.
631
632 .. method:: enter_async_context(cm)
633 :async:
634
635 Similar to :meth:`ExitStack.enter_context` but expects an asynchronous context
636 manager.
637
638 .. versionchanged:: 3.11
639 Raises :exc:`TypeError` instead of :exc:`AttributeError` if *cm*
640 is not an asynchronous context manager.
641
642 .. method:: push_async_exit(exit)
643
644 Similar to :meth:`ExitStack.push` but expects either an asynchronous context manager
645 or a coroutine function.
646
647 .. method:: push_async_callback(callback, /, *args, **kwds)
648
649 Similar to :meth:`ExitStack.callback` but expects a coroutine function.
650
651 .. method:: aclose()
652 :async:
653
654 Similar to :meth:`ExitStack.close` but properly handles awaitables.
655
656 Continuing the example for :func:`asynccontextmanager`::
657
658 async with AsyncExitStack() as stack:
659 connections = [await stack.enter_async_context(get_connection())
660 for i in range(5)]
661 # All opened connections will automatically be released at the end of
662 # the async with statement, even if attempts to open a connection
663 # later in the list raise an exception.
664
665 .. versionadded:: 3.7
666
667 Examples and Recipes
668 --------------------
669
670 This section describes some examples and recipes for making effective use of
671 the tools provided by :mod:`contextlib`.
672
673
674 Supporting a variable number of context managers
675 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
676
677 The primary use case for :class:`ExitStack` is the one given in the class
678 documentation: supporting a variable number of context managers and other
679 cleanup operations in a single :keyword:`with` statement. The variability
680 may come from the number of context managers needed being driven by user
681 input (such as opening a user specified collection of files), or from
682 some of the context managers being optional::
683
684 with ExitStack() as stack:
685 for resource in resources:
686 stack.enter_context(resource)
687 if need_special_resource():
688 special = acquire_special_resource()
689 stack.callback(release_special_resource, special)
690 # Perform operations that use the acquired resources
691
692 As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with`
693 statements to manage arbitrary resources that don't natively support the
694 context management protocol.
695
696
697 Catching exceptions from ``__enter__`` methods
698 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
699
700 It is occasionally desirable to catch exceptions from an ``__enter__``
701 method implementation, *without* inadvertently catching exceptions from
702 the :keyword:`with` statement body or the context manager's ``__exit__``
703 method. By using :class:`ExitStack` the steps in the context management
704 protocol can be separated slightly in order to allow this::
705
706 stack = ExitStack()
707 try:
708 x = stack.enter_context(cm)
709 except Exception:
710 # handle __enter__ exception
711 else:
712 with stack:
713 # Handle normal case
714
715 Actually needing to do this is likely to indicate that the underlying API
716 should be providing a direct resource management interface for use with
717 :keyword:`try`/:keyword:`except`/:keyword:`finally` statements, but not
718 all APIs are well designed in that regard. When a context manager is the
719 only resource management API provided, then :class:`ExitStack` can make it
720 easier to handle various situations that can't be handled directly in a
721 :keyword:`with` statement.
722
723
724 Cleaning up in an ``__enter__`` implementation
725 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
726
727 As noted in the documentation of :meth:`ExitStack.push`, this
728 method can be useful in cleaning up an already allocated resource if later
729 steps in the :meth:`~object.__enter__` implementation fail.
730
731 Here's an example of doing this for a context manager that accepts resource
732 acquisition and release functions, along with an optional validation function,
733 and maps them to the context management protocol::
734
735 from contextlib import contextmanager, AbstractContextManager, ExitStack
736
737 class ResourceManager(AbstractContextManager):
738
739 def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
740 self.acquire_resource = acquire_resource
741 self.release_resource = release_resource
742 if check_resource_ok is None:
743 def check_resource_ok(resource):
744 return True
745 self.check_resource_ok = check_resource_ok
746
747 @contextmanager
748 def _cleanup_on_error(self):
749 with ExitStack() as stack:
750 stack.push(self)
751 yield
752 # The validation check passed and didn't raise an exception
753 # Accordingly, we want to keep the resource, and pass it
754 # back to our caller
755 stack.pop_all()
756
757 def __enter__(self):
758 resource = self.acquire_resource()
759 with self._cleanup_on_error():
760 if not self.check_resource_ok(resource):
761 msg = "Failed validation for {!r}"
762 raise RuntimeError(msg.format(resource))
763 return resource
764
765 def __exit__(self, *exc_details):
766 # We don't need to duplicate any of our resource release logic
767 self.release_resource()
768
769
770 Replacing any use of ``try-finally`` and flag variables
771 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
772
773 A pattern you will sometimes see is a ``try-finally`` statement with a flag
774 variable to indicate whether or not the body of the ``finally`` clause should
775 be executed. In its simplest form (that can't already be handled just by
776 using an ``except`` clause instead), it looks something like this::
777
778 cleanup_needed = True
779 try:
780 result = perform_operation()
781 if result:
782 cleanup_needed = False
783 finally:
784 if cleanup_needed:
785 cleanup_resources()
786
787 As with any ``try`` statement based code, this can cause problems for
788 development and review, because the setup code and the cleanup code can end
789 up being separated by arbitrarily long sections of code.
790
791 :class:`ExitStack` makes it possible to instead register a callback for
792 execution at the end of a ``with`` statement, and then later decide to skip
793 executing that callback::
794
795 from contextlib import ExitStack
796
797 with ExitStack() as stack:
798 stack.callback(cleanup_resources)
799 result = perform_operation()
800 if result:
801 stack.pop_all()
802
803 This allows the intended cleanup behaviour to be made explicit up front,
804 rather than requiring a separate flag variable.
805
806 If a particular application uses this pattern a lot, it can be simplified
807 even further by means of a small helper class::
808
809 from contextlib import ExitStack
810
811 class Callback(ExitStack):
812 def __init__(self, callback, /, *args, **kwds):
813 super().__init__()
814 self.callback(callback, *args, **kwds)
815
816 def cancel(self):
817 self.pop_all()
818
819 with Callback(cleanup_resources) as cb:
820 result = perform_operation()
821 if result:
822 cb.cancel()
823
824 If the resource cleanup isn't already neatly bundled into a standalone
825 function, then it is still possible to use the decorator form of
826 :meth:`ExitStack.callback` to declare the resource cleanup in
827 advance::
828
829 from contextlib import ExitStack
830
831 with ExitStack() as stack:
832 @stack.callback
833 def cleanup_resources():
834 ...
835 result = perform_operation()
836 if result:
837 stack.pop_all()
838
839 Due to the way the decorator protocol works, a callback function
840 declared this way cannot take any parameters. Instead, any resources to
841 be released must be accessed as closure variables.
842
843
844 Using a context manager as a function decorator
845 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
846
847 :class:`ContextDecorator` makes it possible to use a context manager in
848 both an ordinary ``with`` statement and also as a function decorator.
849
850 For example, it is sometimes useful to wrap functions or groups of statements
851 with a logger that can track the time of entry and time of exit. Rather than
852 writing both a function decorator and a context manager for the task,
853 inheriting from :class:`ContextDecorator` provides both capabilities in a
854 single definition::
855
856 from contextlib import ContextDecorator
857 import logging
858
859 logging.basicConfig(level=logging.INFO)
860
861 class track_entry_and_exit(ContextDecorator):
862 def __init__(self, name):
863 self.name = name
864
865 def __enter__(self):
866 logging.info('Entering: %s', self.name)
867
868 def __exit__(self, exc_type, exc, exc_tb):
869 logging.info('Exiting: %s', self.name)
870
871 Instances of this class can be used as both a context manager::
872
873 with track_entry_and_exit('widget loader'):
874 print('Some time consuming activity goes here')
875 load_widget()
876
877 And also as a function decorator::
878
879 @track_entry_and_exit('widget loader')
880 def activity():
881 print('Some time consuming activity goes here')
882 load_widget()
883
884 Note that there is one additional limitation when using context managers
885 as function decorators: there's no way to access the return value of
886 :meth:`~object.__enter__`. If that value is needed, then it is still necessary to use
887 an explicit ``with`` statement.
888
889 .. seealso::
890
891 :pep:`343` - The "with" statement
892 The specification, background, and examples for the Python :keyword:`with`
893 statement.
894
895 .. _single-use-reusable-and-reentrant-cms:
896
897 Single use, reusable and reentrant context managers
898 ---------------------------------------------------
899
900 Most context managers are written in a way that means they can only be
901 used effectively in a :keyword:`with` statement once. These single use
902 context managers must be created afresh each time they're used -
903 attempting to use them a second time will trigger an exception or
904 otherwise not work correctly.
905
906 This common limitation means that it is generally advisable to create
907 context managers directly in the header of the :keyword:`with` statement
908 where they are used (as shown in all of the usage examples above).
909
910 Files are an example of effectively single use context managers, since
911 the first :keyword:`with` statement will close the file, preventing any
912 further IO operations using that file object.
913
914 Context managers created using :func:`contextmanager` are also single use
915 context managers, and will complain about the underlying generator failing
916 to yield if an attempt is made to use them a second time::
917
918 >>> from contextlib import contextmanager
919 >>> @contextmanager
920 ... def singleuse():
921 ... print("Before")
922 ... yield
923 ... print("After")
924 ...
925 >>> cm = singleuse()
926 >>> with cm:
927 ... pass
928 ...
929 Before
930 After
931 >>> with cm:
932 ... pass
933 ...
934 Traceback (most recent call last):
935 ...
936 RuntimeError: generator didn't yield
937
938
939 .. _reentrant-cms:
940
941 Reentrant context managers
942 ^^^^^^^^^^^^^^^^^^^^^^^^^^
943
944 More sophisticated context managers may be "reentrant". These context
945 managers can not only be used in multiple :keyword:`with` statements,
946 but may also be used *inside* a :keyword:`!with` statement that is already
947 using the same context manager.
948
949 :class:`threading.RLock` is an example of a reentrant context manager, as are
950 :func:`suppress`, :func:`redirect_stdout`, and :func:`chdir`. Here's a very
951 simple example of reentrant use::
952
953 >>> from contextlib import redirect_stdout
954 >>> from io import StringIO
955 >>> stream = StringIO()
956 >>> write_to_stream = redirect_stdout(stream)
957 >>> with write_to_stream:
958 ... print("This is written to the stream rather than stdout")
959 ... with write_to_stream:
960 ... print("This is also written to the stream")
961 ...
962 >>> print("This is written directly to stdout")
963 This is written directly to stdout
964 >>> print(stream.getvalue())
965 This is written to the stream rather than stdout
966 This is also written to the stream
967
968 Real world examples of reentrancy are more likely to involve multiple
969 functions calling each other and hence be far more complicated than this
970 example.
971
972 Note also that being reentrant is *not* the same thing as being thread safe.
973 :func:`redirect_stdout`, for example, is definitely not thread safe, as it
974 makes a global modification to the system state by binding :data:`sys.stdout`
975 to a different stream.
976
977
978 .. _reusable-cms:
979
980 Reusable context managers
981 ^^^^^^^^^^^^^^^^^^^^^^^^^
982
983 Distinct from both single use and reentrant context managers are "reusable"
984 context managers (or, to be completely explicit, "reusable, but not
985 reentrant" context managers, since reentrant context managers are also
986 reusable). These context managers support being used multiple times, but
987 will fail (or otherwise not work correctly) if the specific context manager
988 instance has already been used in a containing with statement.
989
990 :class:`threading.Lock` is an example of a reusable, but not reentrant,
991 context manager (for a reentrant lock, it is necessary to use
992 :class:`threading.RLock` instead).
993
994 Another example of a reusable, but not reentrant, context manager is
995 :class:`ExitStack`, as it invokes *all* currently registered callbacks
996 when leaving any with statement, regardless of where those callbacks
997 were added::
998
999 >>> from contextlib import ExitStack
1000 >>> stack = ExitStack()
1001 >>> with stack:
1002 ... stack.callback(print, "Callback: from first context")
1003 ... print("Leaving first context")
1004 ...
1005 Leaving first context
1006 Callback: from first context
1007 >>> with stack:
1008 ... stack.callback(print, "Callback: from second context")
1009 ... print("Leaving second context")
1010 ...
1011 Leaving second context
1012 Callback: from second context
1013 >>> with stack:
1014 ... stack.callback(print, "Callback: from outer context")
1015 ... with stack:
1016 ... stack.callback(print, "Callback: from inner context")
1017 ... print("Leaving inner context")
1018 ... print("Leaving outer context")
1019 ...
1020 Leaving inner context
1021 Callback: from inner context
1022 Callback: from outer context
1023 Leaving outer context
1024
1025 As the output from the example shows, reusing a single stack object across
1026 multiple with statements works correctly, but attempting to nest them
1027 will cause the stack to be cleared at the end of the innermost with
1028 statement, which is unlikely to be desirable behaviour.
1029
1030 Using separate :class:`ExitStack` instances instead of reusing a single
1031 instance avoids that problem::
1032
1033 >>> from contextlib import ExitStack
1034 >>> with ExitStack() as outer_stack:
1035 ... outer_stack.callback(print, "Callback: from outer context")
1036 ... with ExitStack() as inner_stack:
1037 ... inner_stack.callback(print, "Callback: from inner context")
1038 ... print("Leaving inner context")
1039 ... print("Leaving outer context")
1040 ...
1041 Leaving inner context
1042 Callback: from inner context
1043 Leaving outer context
1044 Callback: from outer context