The contextlib library¶
- class AbstractContextManager¶
An abstract base class for asynchronous context managers
This class can be used to check whether some object is an asynchronous context manager. If a class may inherit from
AbstractContextManager, in which case it must implement an
__aenter__method; the default
__aenter__returns the asynchronous context manager itself.
New in version 1.1.0.
- @contextmanager(func: (...) → async iter T) (...) → async with T ¶
Create an asynchronous context manager out of an asynchronous generator function
This is intended as a decorator for an asynchronous generator function. The asynchronous generator should
yieldonce, at which point the body of the context manager executes. If
yieldprovides a value, this becomes the value of the context in the block.
@contextmanager async def Context(*args, **kwargs): # __aenter__ yield # context value # __aexit__
Note that if an exception ends the context block, it gets re-raised at the
yieldinside the asynchronous generator (via
athrow()). In order to handle this exception, the
yieldshould be wrapped in a
- async with closing(thing: AC) as :AC¶
Create an asynchronous context manager to
Once entered, the context manager guarantees to
await thing.aclose()at the end of its block. This is useful for safe cleanup even if errors occur.
closingfor objects that need reliable cleanup but do not support the context manager protocol. For example, it is advisable to prompty clean up any asynchronous iterator that holds resources:
import asyncstdlib as a async with a.closing(a.iter(something)) as async_iter: async for element in async_iter: ...
- async with nullcontext(enter_result: T) as :T¶
Create an asynchronous context manager that only returns
Intended as a neutral element, a
nullcontextserves as a placeholder where an async context manager is semantically required but not meaningfull. This allows for an optional async context manager with a default
nullcontext, or to prevent closing of an existing context manager in an
async def safe_fetch(source): if not isinstance(source, AsyncIterator): # use a context manager if required ... acm = a.closing(iter(source)) else: # ... or a neutral placeholder acm = a.nullcontext(source) async with acm as async_iter: ...
- class ExitStack¶
Context Manager emulating several nested Context Managers
enter_context()can be used to emulate entering further context managers. When unwinding the stack, context managers are exited in LIFO order, effectively emulating nested context managers. The primary use-case is programmatically entering optional or a dynamically sized number of context managers.
- await enter_context(cm: (async) with T) T ¶
Enter the supplied context manager, and register it for exit if successful
This method is equivalent to using
async withstatement; if
cmcan only be used in a
withstatement, it is silently promoted. The stack will enter
cmand, if successful, ensure that
cmis exited when the stack unwinds. The return value of this method is the value that
cmprovides in an
# explicitly enter context managers async with cm_a as value_a, cm_b as value_b: ... # programmatically enter context managers async with a.ExitStack() as exit_stack: value_a = exit_stack.enter_context(cm_a) value_b = exit_stack.enter_context(cm_b) ...
When unwinding, the context manager is exited as if it were part of a regular stack of
async with(that is, in LIFO order). It receives the current exception details and may suppress it as usual. As with the
async withstatement, if the context cannot be entered (that is,
await cm.__aenter__()throws an exception) it is not exited either.
- callback(callback: T as (*args, **kwargs) -> None, *args, **kwargs) T ¶
Registers an arbitrary callback to be called with arguments on unwinding
The callback is invoked as
await callback(*args, **kwargs)when the stack unwinds. It does not receive the current exception details and cannot suppress the exception handled by the stack. The callback is treated as async neutral, i.e. it may be a synchronous function.
This method does not change its argument, and can be used as a context manager.
- push(exit: T as (Type[BaseException], BaseException, traceback) -> (await) bool) T ¶
Registers a callback with the standard
exit – the exit callback to invoke on
When the stack is unwound, callbacks receive the current exception details, and are expected to return
Trueif the exception should be suppressed. Two normalizations are applied to match the
__aexit__method, this method is used instead.
__exit__method, this method is used instead. It is automatically treated as asynchronous.
exitis not asynchronous, it is automatically treated as such.
Regardless of internal normalizations,
exitis always returned unchanged. This allows using
pushas a decorator.
When receiving a context manager, this method only sets up
__exit__for being called. It does not enter the context manager. If a context manager must also be entered, use
- pop_all() asyncstdlib.contextlib.ExitStack ¶
Transfer all exit callbacks to a new
ExitStackowning all previously registered callbacks
The responsibility of invoking previously registered handlers is fully transferred to the new
ExitStack. Neither calling this method, nor closing the original
async withstatement) invokes these callbacks. Note that callbacks added after calling
pop_all()are not affected by this.
- await aclose()¶
Immediately unwind the context stack
Unlike the regular
contextlib.ExitStack.close()method, this method is
asyncand follows the
New in version 1.1.0.