blob: de989a001c6dfbc0f3885ca55a212568b22c15ee [file] [log] [blame]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001"""Utilities for with-statement contexts. See PEP 343."""
Brett Cannon9e080e02016-04-08 12:15:27 -07002import abc
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003import sys
Jelle Zijlstra57161aa2017-06-09 08:21:47 -07004import _collections_abc
Nick Coghlan3267a302012-05-21 22:54:43 +10005from collections import deque
Christian Heimes81ee3ef2008-05-04 22:42:01 +00006from functools import wraps
jdemeyer23ab5ee2018-04-13 14:22:46 +02007from types import MethodType
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00008
Jesse-Bakker0784a2e2017-11-23 01:23:28 +01009__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
Jelle Zijlstra176baa32017-12-13 17:19:17 -080010 "AbstractContextManager", "AbstractAsyncContextManager",
Ilya Kulakov1aa094f2018-01-25 12:51:18 -080011 "AsyncExitStack", "ContextDecorator", "ExitStack",
Jelle Zijlstra2e624692017-04-30 18:25:58 -070012 "redirect_stdout", "redirect_stderr", "suppress"]
Brett Cannon9e080e02016-04-08 12:15:27 -070013
14
15class AbstractContextManager(abc.ABC):
16
17 """An abstract base class for context managers."""
18
19 def __enter__(self):
20 """Return `self` upon entering the runtime context."""
21 return self
22
23 @abc.abstractmethod
24 def __exit__(self, exc_type, exc_value, traceback):
25 """Raise any exception triggered within the runtime context."""
26 return None
27
28 @classmethod
29 def __subclasshook__(cls, C):
30 if cls is AbstractContextManager:
Jelle Zijlstra57161aa2017-06-09 08:21:47 -070031 return _collections_abc._check_methods(C, "__enter__", "__exit__")
Brett Cannon9e080e02016-04-08 12:15:27 -070032 return NotImplemented
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000033
Michael Foordb3a89842010-06-30 12:17:50 +000034
Jelle Zijlstra176baa32017-12-13 17:19:17 -080035class AbstractAsyncContextManager(abc.ABC):
36
37 """An abstract base class for asynchronous context managers."""
38
39 async def __aenter__(self):
40 """Return `self` upon entering the runtime context."""
41 return self
42
43 @abc.abstractmethod
44 async def __aexit__(self, exc_type, exc_value, traceback):
45 """Raise any exception triggered within the runtime context."""
46 return None
47
48 @classmethod
49 def __subclasshook__(cls, C):
50 if cls is AbstractAsyncContextManager:
51 return _collections_abc._check_methods(C, "__aenter__",
52 "__aexit__")
53 return NotImplemented
54
55
Michael Foordb3a89842010-06-30 12:17:50 +000056class ContextDecorator(object):
57 "A base class or mixin that enables context managers to work as decorators."
Nick Coghlan0ded3e32011-05-05 23:49:25 +100058
59 def _recreate_cm(self):
60 """Return a recreated instance of self.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100061
Nick Coghlan3267a302012-05-21 22:54:43 +100062 Allows an otherwise one-shot context manager like
Nick Coghlan0ded3e32011-05-05 23:49:25 +100063 _GeneratorContextManager to support use as
Nick Coghlan3267a302012-05-21 22:54:43 +100064 a decorator via implicit recreation.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100065
Nick Coghlan3267a302012-05-21 22:54:43 +100066 This is a private interface just for _GeneratorContextManager.
67 See issue #11647 for details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100068 """
69 return self
70
Michael Foordb3a89842010-06-30 12:17:50 +000071 def __call__(self, func):
72 @wraps(func)
73 def inner(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100074 with self._recreate_cm():
Michael Foordb3a89842010-06-30 12:17:50 +000075 return func(*args, **kwds)
76 return inner
77
78
Jelle Zijlstra2e624692017-04-30 18:25:58 -070079class _GeneratorContextManagerBase:
80 """Shared functionality for @contextmanager and @asynccontextmanager."""
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000081
Serhiy Storchaka101ff352015-06-28 17:06:07 +030082 def __init__(self, func, args, kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100083 self.gen = func(*args, **kwds)
84 self.func, self.args, self.kwds = func, args, kwds
Nick Coghlan059def52013-10-26 18:08:15 +100085 # Issue 19330: ensure context manager instances have good docstrings
86 doc = getattr(func, "__doc__", None)
87 if doc is None:
88 doc = type(self).__doc__
89 self.__doc__ = doc
90 # Unfortunately, this still doesn't provide good help output when
91 # inspecting the created context manager instances, since pydoc
92 # currently bypasses the instance docstring and shows the docstring
93 # for the class instead.
94 # See http://bugs.python.org/issue19404 for more details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100095
Jelle Zijlstra2e624692017-04-30 18:25:58 -070096
97class _GeneratorContextManager(_GeneratorContextManagerBase,
98 AbstractContextManager,
99 ContextDecorator):
100 """Helper for @contextmanager decorator."""
101
Nick Coghlan0ded3e32011-05-05 23:49:25 +1000102 def _recreate_cm(self):
103 # _GCM instances are one-shot context managers, so the
104 # CM must be recreated each time a decorated function is
105 # called
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300106 return self.__class__(self.func, self.args, self.kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000107
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000108 def __enter__(self):
Martin Teichmanndd0e0872018-01-28 05:17:46 +0100109 # do not keep args and kwds alive unnecessarily
110 # they are only needed for recreation, which is not possible anymore
111 del self.args, self.kwds, self.func
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000112 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000113 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000114 except StopIteration:
Nick Coghlan8608d262013-10-20 00:30:51 +1000115 raise RuntimeError("generator didn't yield") from None
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000116
117 def __exit__(self, type, value, traceback):
118 if type is None:
119 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000120 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000121 except StopIteration:
svelankar00c75e92017-04-11 05:11:13 -0400122 return False
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000123 else:
124 raise RuntimeError("generator didn't stop")
125 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000126 if value is None:
127 # Need to force instantiation so we can reliably
128 # tell if we get the same exception back
129 value = type()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000130 try:
131 self.gen.throw(type, value, traceback)
Guido van Rossumb940e112007-01-10 16:19:56 +0000132 except StopIteration as exc:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400133 # Suppress StopIteration *unless* it's the same exception that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 # was passed to throw(). This prevents a StopIteration
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400135 # raised inside the "with" statement from being suppressed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136 return exc is not value
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400137 except RuntimeError as exc:
Nathaniel J. Smithaf88e7e2017-02-12 03:37:24 -0800138 # Don't re-raise the passed in exception. (issue27122)
Gregory P. Smithba2ecd62016-06-14 09:19:20 -0700139 if exc is value:
140 return False
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400141 # Likewise, avoid suppressing if a StopIteration exception
142 # was passed to throw() and later wrapped into a RuntimeError
143 # (see PEP 479).
svelankar00c75e92017-04-11 05:11:13 -0400144 if type is StopIteration and exc.__cause__ is value:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400145 return False
146 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000147 except:
148 # only re-raise if it's *not* the exception that was
149 # passed to throw(), because __exit__() must not raise
150 # an exception unless __exit__() itself failed. But throw()
151 # has to raise the exception to signal propagation, so this
152 # fixes the impedance mismatch between the throw() protocol
153 # and the __exit__() protocol.
154 #
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700155 # This cannot use 'except BaseException as exc' (as in the
156 # async implementation) to maintain compatibility with
157 # Python 2, where old-style class exceptions are not caught
158 # by 'except BaseException'.
svelankar00c75e92017-04-11 05:11:13 -0400159 if sys.exc_info()[1] is value:
160 return False
161 raise
162 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000163
164
Jelle Zijlstra176baa32017-12-13 17:19:17 -0800165class _AsyncGeneratorContextManager(_GeneratorContextManagerBase,
166 AbstractAsyncContextManager):
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700167 """Helper for @asynccontextmanager."""
168
169 async def __aenter__(self):
170 try:
171 return await self.gen.__anext__()
172 except StopAsyncIteration:
173 raise RuntimeError("generator didn't yield") from None
174
175 async def __aexit__(self, typ, value, traceback):
176 if typ is None:
177 try:
178 await self.gen.__anext__()
179 except StopAsyncIteration:
180 return
181 else:
182 raise RuntimeError("generator didn't stop")
183 else:
184 if value is None:
185 value = typ()
186 # See _GeneratorContextManager.__exit__ for comments on subtleties
187 # in this implementation
188 try:
189 await self.gen.athrow(typ, value, traceback)
Yury Selivanov52698c72018-06-07 20:31:26 -0400190 raise RuntimeError("generator didn't stop after athrow()")
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700191 except StopAsyncIteration as exc:
192 return exc is not value
193 except RuntimeError as exc:
194 if exc is value:
195 return False
196 # Avoid suppressing if a StopIteration exception
197 # was passed to throw() and later wrapped into a RuntimeError
198 # (see PEP 479 for sync generators; async generators also
199 # have this behavior). But do this only if the exception wrapped
200 # by the RuntimeError is actully Stop(Async)Iteration (see
201 # issue29692).
202 if isinstance(value, (StopIteration, StopAsyncIteration)):
203 if exc.__cause__ is value:
204 return False
205 raise
206 except BaseException as exc:
207 if exc is not value:
208 raise
209
210
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000211def contextmanager(func):
212 """@contextmanager decorator.
213
214 Typical usage:
215
216 @contextmanager
217 def some_generator(<arguments>):
218 <setup>
219 try:
220 yield <value>
221 finally:
222 <cleanup>
223
224 This makes this:
225
226 with some_generator(<arguments>) as <variable>:
227 <body>
228
229 equivalent to this:
230
231 <setup>
232 try:
233 <variable> = <value>
234 <body>
235 finally:
236 <cleanup>
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000237 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000238 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000239 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300240 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000241 return helper
242
243
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700244def asynccontextmanager(func):
245 """@asynccontextmanager decorator.
246
247 Typical usage:
248
249 @asynccontextmanager
250 async def some_async_generator(<arguments>):
251 <setup>
252 try:
253 yield <value>
254 finally:
255 <cleanup>
256
257 This makes this:
258
259 async with some_async_generator(<arguments>) as <variable>:
260 <body>
261
262 equivalent to this:
263
264 <setup>
265 try:
266 <variable> = <value>
267 <body>
268 finally:
269 <cleanup>
270 """
271 @wraps(func)
272 def helper(*args, **kwds):
273 return _AsyncGeneratorContextManager(func, args, kwds)
274 return helper
275
276
Brett Cannon9e080e02016-04-08 12:15:27 -0700277class closing(AbstractContextManager):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000278 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000279
280 Code like this:
281
282 with closing(<module>.open(<arguments>)) as f:
283 <block>
284
285 is equivalent to this:
286
287 f = <module>.open(<arguments>)
288 try:
289 <block>
290 finally:
291 f.close()
292
293 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000294 def __init__(self, thing):
295 self.thing = thing
296 def __enter__(self):
297 return self.thing
298 def __exit__(self, *exc_info):
299 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000300
Berker Peksagbb44fe02014-11-28 23:28:06 +0200301
Brett Cannon9e080e02016-04-08 12:15:27 -0700302class _RedirectStream(AbstractContextManager):
Berker Peksagbb44fe02014-11-28 23:28:06 +0200303
304 _stream = None
305
306 def __init__(self, new_target):
307 self._new_target = new_target
308 # We use a list of old targets to make this CM re-entrant
309 self._old_targets = []
310
311 def __enter__(self):
312 self._old_targets.append(getattr(sys, self._stream))
313 setattr(sys, self._stream, self._new_target)
314 return self._new_target
315
316 def __exit__(self, exctype, excinst, exctb):
317 setattr(sys, self._stream, self._old_targets.pop())
318
319
320class redirect_stdout(_RedirectStream):
321 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000322
323 # How to send help() to stderr
324 with redirect_stdout(sys.stderr):
325 help(dir)
326
327 # How to write help() to a file
328 with open('help.txt', 'w') as f:
329 with redirect_stdout(f):
330 help(pow)
331 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000332
Berker Peksagbb44fe02014-11-28 23:28:06 +0200333 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000334
Nick Coghlan8608d262013-10-20 00:30:51 +1000335
Berker Peksagbb44fe02014-11-28 23:28:06 +0200336class redirect_stderr(_RedirectStream):
337 """Context manager for temporarily redirecting stderr to another file."""
338
339 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700340
Nick Coghlan8608d262013-10-20 00:30:51 +1000341
Brett Cannon9e080e02016-04-08 12:15:27 -0700342class suppress(AbstractContextManager):
Nick Coghlan240f86d2013-10-17 23:40:57 +1000343 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700344
Nick Coghlan8608d262013-10-20 00:30:51 +1000345 After the exception is suppressed, execution proceeds with the next
346 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700347
Nick Coghlan8608d262013-10-20 00:30:51 +1000348 with suppress(FileNotFoundError):
349 os.remove(somefile)
350 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700351 """
Nick Coghlan059def52013-10-26 18:08:15 +1000352
353 def __init__(self, *exceptions):
354 self._exceptions = exceptions
355
356 def __enter__(self):
357 pass
358
359 def __exit__(self, exctype, excinst, exctb):
360 # Unlike isinstance and issubclass, CPython exception handling
361 # currently only looks at the concrete type hierarchy (ignoring
362 # the instance and subclass checking hooks). While Guido considers
363 # that a bug rather than a feature, it's a fairly hard one to fix
364 # due to various internal implementation details. suppress provides
365 # the simpler issubclass based semantics, rather than trying to
366 # exactly reproduce the limitations of the CPython interpreter.
367 #
368 # See http://bugs.python.org/issue12029 for more details
369 return exctype is not None and issubclass(exctype, self._exceptions)
370
Nick Coghlan3267a302012-05-21 22:54:43 +1000371
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800372class _BaseExitStack:
373 """A base class for ExitStack and AsyncExitStack."""
Nick Coghlan3267a302012-05-21 22:54:43 +1000374
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800375 @staticmethod
376 def _create_exit_wrapper(cm, cm_exit):
jdemeyer23ab5ee2018-04-13 14:22:46 +0200377 return MethodType(cm_exit, cm)
Nick Coghlan3267a302012-05-21 22:54:43 +1000378
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800379 @staticmethod
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300380 def _create_cb_wrapper(*args, **kwds):
381 callback, *args = args
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800382 def _exit_wrapper(exc_type, exc, tb):
383 callback(*args, **kwds)
384 return _exit_wrapper
Nick Coghlan3267a302012-05-21 22:54:43 +1000385
Nick Coghlan3267a302012-05-21 22:54:43 +1000386 def __init__(self):
387 self._exit_callbacks = deque()
388
389 def pop_all(self):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800390 """Preserve the context stack by transferring it to a new instance."""
Nick Coghlan3267a302012-05-21 22:54:43 +1000391 new_stack = type(self)()
392 new_stack._exit_callbacks = self._exit_callbacks
393 self._exit_callbacks = deque()
394 return new_stack
395
Nick Coghlan3267a302012-05-21 22:54:43 +1000396 def push(self, exit):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800397 """Registers a callback with the standard __exit__ method signature.
Nick Coghlan3267a302012-05-21 22:54:43 +1000398
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800399 Can suppress exceptions the same way __exit__ method can.
Nick Coghlan3267a302012-05-21 22:54:43 +1000400 Also accepts any object with an __exit__ method (registering a call
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800401 to the method instead of the object itself).
Nick Coghlan3267a302012-05-21 22:54:43 +1000402 """
403 # We use an unbound method rather than a bound method to follow
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800404 # the standard lookup behaviour for special methods.
Nick Coghlan3267a302012-05-21 22:54:43 +1000405 _cb_type = type(exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800406
Nick Coghlan3267a302012-05-21 22:54:43 +1000407 try:
408 exit_method = _cb_type.__exit__
409 except AttributeError:
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800410 # Not a context manager, so assume it's a callable.
411 self._push_exit_callback(exit)
Nick Coghlan3267a302012-05-21 22:54:43 +1000412 else:
413 self._push_cm_exit(exit, exit_method)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800414 return exit # Allow use as a decorator.
Nick Coghlan3267a302012-05-21 22:54:43 +1000415
416 def enter_context(self, cm):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800417 """Enters the supplied context manager.
Nick Coghlan3267a302012-05-21 22:54:43 +1000418
419 If successful, also pushes its __exit__ method as a callback and
420 returns the result of the __enter__ method.
421 """
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800422 # We look up the special methods on the type to match the with
423 # statement.
Nick Coghlan3267a302012-05-21 22:54:43 +1000424 _cm_type = type(cm)
425 _exit = _cm_type.__exit__
426 result = _cm_type.__enter__(cm)
427 self._push_cm_exit(cm, _exit)
428 return result
429
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300430 def callback(*args, **kwds):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800431 """Registers an arbitrary callback and arguments.
432
433 Cannot suppress exceptions.
434 """
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300435 if len(args) >= 2:
436 self, callback, *args = args
437 elif not args:
438 raise TypeError("descriptor 'callback' of '_BaseExitStack' object "
439 "needs an argument")
440 elif 'callback' in kwds:
441 callback = kwds.pop('callback')
442 self, *args = args
443 import warnings
444 warnings.warn("Passing 'callback' as keyword argument is deprecated",
445 DeprecationWarning, stacklevel=2)
446 else:
447 raise TypeError('callback expected at least 1 positional argument, '
448 'got %d' % (len(args)-1))
449
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800450 _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
451
452 # We changed the signature, so using @wraps is not appropriate, but
453 # setting __wrapped__ may still help with introspection.
454 _exit_wrapper.__wrapped__ = callback
455 self._push_exit_callback(_exit_wrapper)
456 return callback # Allow use as a decorator
Serhiy Storchakad53cf992019-05-06 22:40:27 +0300457 callback.__text_signature__ = '($self, callback, /, *args, **kwds)'
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800458
459 def _push_cm_exit(self, cm, cm_exit):
460 """Helper to correctly register callbacks to __exit__ methods."""
461 _exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800462 self._push_exit_callback(_exit_wrapper, True)
463
464 def _push_exit_callback(self, callback, is_sync=True):
465 self._exit_callbacks.append((is_sync, callback))
466
467
468# Inspired by discussions on http://bugs.python.org/issue13585
469class ExitStack(_BaseExitStack, AbstractContextManager):
470 """Context manager for dynamic management of a stack of exit callbacks.
471
472 For example:
473 with ExitStack() as stack:
474 files = [stack.enter_context(open(fname)) for fname in filenames]
475 # All opened files will automatically be closed at the end of
476 # the with statement, even if attempts to open files later
477 # in the list raise an exception.
478 """
479
480 def __enter__(self):
481 return self
Nick Coghlan3267a302012-05-21 22:54:43 +1000482
Nick Coghlan3267a302012-05-21 22:54:43 +1000483 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000484 received_exc = exc_details[0] is not None
485
Nick Coghlan77452fc2012-06-01 22:48:32 +1000486 # We manipulate the exception state so it behaves as though
487 # we were actually nesting multiple with statements
488 frame_exc = sys.exc_info()[1]
489 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000490 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000491 while 1:
492 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000493 if exc_context is old_exc:
494 # Context is already set correctly (see issue 20317)
495 return
496 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000497 break
498 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000499 # Change the end of the chain to point to the exception
500 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000501 new_exc.__context__ = old_exc
502
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000503 # Callbacks are invoked in LIFO order to match the behaviour of
504 # nested context managers
505 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000506 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000507 while self._exit_callbacks:
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800508 is_sync, cb = self._exit_callbacks.pop()
509 assert is_sync
Nick Coghlan3267a302012-05-21 22:54:43 +1000510 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000511 if cb(*exc_details):
512 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000513 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000514 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000515 except:
516 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000517 # simulate the stack of exceptions by setting the context
518 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000519 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000520 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000521 if pending_raise:
522 try:
523 # bare "raise exc_details[1]" replaces our carefully
524 # set-up context
525 fixed_ctx = exc_details[1].__context__
526 raise exc_details[1]
527 except BaseException:
528 exc_details[1].__context__ = fixed_ctx
529 raise
530 return received_exc and suppressed_exc
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100531
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800532 def close(self):
533 """Immediately unwind the context stack."""
534 self.__exit__(None, None, None)
535
536
537# Inspired by discussions on https://bugs.python.org/issue29302
538class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):
539 """Async context manager for dynamic management of a stack of exit
540 callbacks.
541
542 For example:
543 async with AsyncExitStack() as stack:
544 connections = [await stack.enter_async_context(get_connection())
545 for i in range(5)]
546 # All opened connections will automatically be released at the
547 # end of the async with statement, even if attempts to open a
548 # connection later in the list raise an exception.
549 """
550
551 @staticmethod
552 def _create_async_exit_wrapper(cm, cm_exit):
jdemeyer23ab5ee2018-04-13 14:22:46 +0200553 return MethodType(cm_exit, cm)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800554
555 @staticmethod
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300556 def _create_async_cb_wrapper(*args, **kwds):
557 callback, *args = args
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800558 async def _exit_wrapper(exc_type, exc, tb):
559 await callback(*args, **kwds)
560 return _exit_wrapper
561
562 async def enter_async_context(self, cm):
563 """Enters the supplied async context manager.
564
565 If successful, also pushes its __aexit__ method as a callback and
566 returns the result of the __aenter__ method.
567 """
568 _cm_type = type(cm)
569 _exit = _cm_type.__aexit__
570 result = await _cm_type.__aenter__(cm)
571 self._push_async_cm_exit(cm, _exit)
572 return result
573
574 def push_async_exit(self, exit):
575 """Registers a coroutine function with the standard __aexit__ method
576 signature.
577
578 Can suppress exceptions the same way __aexit__ method can.
579 Also accepts any object with an __aexit__ method (registering a call
580 to the method instead of the object itself).
581 """
582 _cb_type = type(exit)
583 try:
584 exit_method = _cb_type.__aexit__
585 except AttributeError:
586 # Not an async context manager, so assume it's a coroutine function
587 self._push_exit_callback(exit, False)
588 else:
589 self._push_async_cm_exit(exit, exit_method)
590 return exit # Allow use as a decorator
591
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300592 def push_async_callback(*args, **kwds):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800593 """Registers an arbitrary coroutine function and arguments.
594
595 Cannot suppress exceptions.
596 """
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300597 if len(args) >= 2:
598 self, callback, *args = args
599 elif not args:
600 raise TypeError("descriptor 'push_async_callback' of "
601 "'AsyncExitStack' object needs an argument")
602 elif 'callback' in kwds:
603 callback = kwds.pop('callback')
604 self, *args = args
605 import warnings
606 warnings.warn("Passing 'callback' as keyword argument is deprecated",
607 DeprecationWarning, stacklevel=2)
608 else:
609 raise TypeError('push_async_callback expected at least 1 '
610 'positional argument, got %d' % (len(args)-1))
611
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800612 _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
613
614 # We changed the signature, so using @wraps is not appropriate, but
615 # setting __wrapped__ may still help with introspection.
616 _exit_wrapper.__wrapped__ = callback
617 self._push_exit_callback(_exit_wrapper, False)
618 return callback # Allow use as a decorator
Serhiy Storchakad53cf992019-05-06 22:40:27 +0300619 push_async_callback.__text_signature__ = '($self, callback, /, *args, **kwds)'
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800620
621 async def aclose(self):
622 """Immediately unwind the context stack."""
623 await self.__aexit__(None, None, None)
624
625 def _push_async_cm_exit(self, cm, cm_exit):
626 """Helper to correctly register coroutine function to __aexit__
627 method."""
628 _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800629 self._push_exit_callback(_exit_wrapper, False)
630
631 async def __aenter__(self):
632 return self
633
634 async def __aexit__(self, *exc_details):
635 received_exc = exc_details[0] is not None
636
637 # We manipulate the exception state so it behaves as though
638 # we were actually nesting multiple with statements
639 frame_exc = sys.exc_info()[1]
640 def _fix_exception_context(new_exc, old_exc):
641 # Context may not be correct, so find the end of the chain
642 while 1:
643 exc_context = new_exc.__context__
644 if exc_context is old_exc:
645 # Context is already set correctly (see issue 20317)
646 return
647 if exc_context is None or exc_context is frame_exc:
648 break
649 new_exc = exc_context
650 # Change the end of the chain to point to the exception
651 # we expect it to reference
652 new_exc.__context__ = old_exc
653
654 # Callbacks are invoked in LIFO order to match the behaviour of
655 # nested context managers
656 suppressed_exc = False
657 pending_raise = False
658 while self._exit_callbacks:
659 is_sync, cb = self._exit_callbacks.pop()
660 try:
661 if is_sync:
662 cb_suppress = cb(*exc_details)
663 else:
664 cb_suppress = await cb(*exc_details)
665
666 if cb_suppress:
667 suppressed_exc = True
668 pending_raise = False
669 exc_details = (None, None, None)
670 except:
671 new_exc_details = sys.exc_info()
672 # simulate the stack of exceptions by setting the context
673 _fix_exception_context(new_exc_details[1], exc_details[1])
674 pending_raise = True
675 exc_details = new_exc_details
676 if pending_raise:
677 try:
678 # bare "raise exc_details[1]" replaces our carefully
679 # set-up context
680 fixed_ctx = exc_details[1].__context__
681 raise exc_details[1]
682 except BaseException:
683 exc_details[1].__context__ = fixed_ctx
684 raise
685 return received_exc and suppressed_exc
686
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100687
688class nullcontext(AbstractContextManager):
689 """Context manager that does no additional processing.
690
691 Used as a stand-in for a normal context manager, when a particular
692 block of code is only sometimes used with a normal context manager:
693
694 cm = optional_cm if condition else nullcontext()
695 with cm:
696 # Perform operation, using optional_cm if condition is True
697 """
698
699 def __init__(self, enter_result=None):
700 self.enter_result = enter_result
701
702 def __enter__(self):
703 return self.enter_result
704
705 def __exit__(self, *excinfo):
706 pass