# Callbacks are invoked in LIFO order to match the behaviour of
# nested context managers
while self._exit_callbacks:
is_sync, cb = self._exit_callbacks.pop()
exc_details = (None, None, None)
new_exc_details = sys.exc_info()
# simulate the stack of exceptions by setting the context
_fix_exception_context(new_exc_details[1], exc_details[1])
exc_details = new_exc_details
# bare "raise exc_details[1]" replaces our carefully
fixed_ctx = exc_details[1].__context__
exc_details[1].__context__ = fixed_ctx
return received_exc and suppressed_exc
"""Immediately unwind the context stack."""
self.__exit__(None, None, None)
# Inspired by discussions on https://bugs.python.org/issue29302
class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):
"""Async context manager for dynamic management of a stack of exit
async with AsyncExitStack() as stack:
connections = [await stack.enter_async_context(get_connection())
# All opened connections will automatically be released at the
# end of the async with statement, even if attempts to open a
# connection later in the list raise an exception.
def _create_async_exit_wrapper(cm, cm_exit):
return MethodType(cm_exit, cm)
def _create_async_cb_wrapper(callback, /, *args, **kwds):
async def _exit_wrapper(exc_type, exc, tb):
await callback(*args, **kwds)
async def enter_async_context(self, cm):
"""Enters the supplied async context manager.
If successful, also pushes its __aexit__ method as a callback and
returns the result of the __aenter__ method.
_exit = _cm_type.__aexit__
result = await _cm_type.__aenter__(cm)
self._push_async_cm_exit(cm, _exit)
def push_async_exit(self, exit):
"""Registers a coroutine function with the standard __aexit__ method
Can suppress exceptions the same way __aexit__ method can.
Also accepts any object with an __aexit__ method (registering a call
to the method instead of the object itself).
exit_method = _cb_type.__aexit__
# Not an async context manager, so assume it's a coroutine function
self._push_exit_callback(exit, False)
self._push_async_cm_exit(exit, exit_method)
return exit # Allow use as a decorator
def push_async_callback(*args, **kwds):
"""Registers an arbitrary coroutine function and arguments.
Cannot suppress exceptions.
self, callback, *args = args
raise TypeError("descriptor 'push_async_callback' of "
"'AsyncExitStack' object needs an argument")
callback = kwds.pop('callback')
warnings.warn("Passing 'callback' as keyword argument is deprecated",
DeprecationWarning, stacklevel=2)
raise TypeError('push_async_callback expected at least 1 '
'positional argument, got %d' % (len(args)-1))
_exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
# We changed the signature, so using @wraps is not appropriate, but
# setting __wrapped__ may still help with introspection.
_exit_wrapper.__wrapped__ = callback
self._push_exit_callback(_exit_wrapper, False)
return callback # Allow use as a decorator
push_async_callback.__text_signature__ = '($self, callback, /, *args, **kwds)'
"""Immediately unwind the context stack."""
await self.__aexit__(None, None, None)
def _push_async_cm_exit(self, cm, cm_exit):
"""Helper to correctly register coroutine function to __aexit__
_exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
self._push_exit_callback(_exit_wrapper, False)
async def __aenter__(self):
async def __aexit__(self, *exc_details):
received_exc = exc_details[0] is not None
# We manipulate the exception state so it behaves as though
# we were actually nesting multiple with statements
frame_exc = sys.exc_info()[1]
def _fix_exception_context(new_exc, old_exc):
# Context may not be correct, so find the end of the chain
exc_context = new_exc.__context__
if exc_context is old_exc:
# Context is already set correctly (see issue 20317)
if exc_context is None or exc_context is frame_exc:
# Change the end of the chain to point to the exception
# we expect it to reference
new_exc.__context__ = old_exc
# Callbacks are invoked in LIFO order to match the behaviour of
# nested context managers
while self._exit_callbacks:
is_sync, cb = self._exit_callbacks.pop()
cb_suppress = cb(*exc_details)
cb_suppress = await cb(*exc_details)
exc_details = (None, None, None)
new_exc_details = sys.exc_info()
# simulate the stack of exceptions by setting the context
_fix_exception_context(new_exc_details[1], exc_details[1])
exc_details = new_exc_details
# bare "raise exc_details[1]" replaces our carefully
fixed_ctx = exc_details[1].__context__
exc_details[1].__context__ = fixed_ctx
return received_exc and suppressed_exc
class nullcontext(AbstractContextManager):
"""Context manager that does no additional processing.
Used as a stand-in for a normal context manager, when a particular
block of code is only sometimes used with a normal context manager:
cm = optional_cm if condition else nullcontext()
# Perform operation, using optional_cm if condition is True
def __init__(self, enter_result=None):
self.enter_result = enter_result
def __exit__(self, *excinfo):