mode.utils.contexts

Context manager utilities.

class mode.utils.contexts.AbstractAsyncContextManager

An abstract base class for asynchronous context managers.

class mode.utils.contexts.AsyncExitStack

Async context manager for dynamic management of a stack of exit callbacks.

Example

>>> async with AsyncExitStack() as stack:
...    connections = [await stack.enter_async_context(get_connection())
...                   for i in range(5)]
...    # 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.
async enter_async_context(cm: AsyncContextManager) → Any

Enters the supplied async context manager.

If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method.

push_async_exit(exit: Union[AsyncContextManager, Callable[..., Awaitable]]) → Union[AsyncContextManager, Callable[..., Awaitable]]

Register coroutine with the standard __aexit__ method signature.

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).

push_async_callback(callback: Callable[..., Awaitable], *args: Any, **kwds: Any) → Callable[..., Awaitable]

Register an arbitrary coroutine function and arguments.

Cannot suppress exceptions.

async aclose() → None

Immediately unwind the context stack.

class mode.utils.contexts.ExitStack

Context manager for dynamic management of a stack of exit callbacks.

For example:
with ExitStack() as stack:

files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception.

close() → None

Immediately unwind the context stack.

mode.utils.contexts.asynccontextmanager(func: Callable) → Callable[..., AsyncContextManager]

asynccontextmanager decorator.

class mode.utils.contexts.nullcontext(enter_result: Any = None)

Context that does nothing.

class mode.utils.contexts.asyncnullcontext(enter_result: Any = None)

Context for async-with statement doing nothing.

enter_result: Any = None