mode.utils.contexts
¶
Context manager utilities.
-
class
mode.utils.contexts.
AbstractAsyncContextManager
[source]¶ An abstract base class for asynchronous context managers.
-
class
mode.utils.contexts.
AsyncExitStack
[source]¶ Async
ExitStack
.Context manager for dynamic management of a stack of exit callbacks.
Examples
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.
-
push_async_exit
(exit: Union[AsyncContextManager, Callable[..., Awaitable]]) → Union[AsyncContextManager, Callable[..., Awaitable]][source]¶ 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).
-
-
class
mode.utils.contexts.
ExitStack
[source]¶ 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.
-
mode.utils.contexts.
asynccontextmanager
(func)[source]¶ @asynccontextmanager decorator.
Typical usage:
@asynccontextmanager async def some_async_generator(<arguments>): <setup> try: yield <value> finally: <cleanup>
This makes this:
async with some_async_generator(<arguments>) as <variable>: <body>
equivalent to this:
<setup> try: <variable> = <value> <body> finally: <cleanup>
-
class
mode.utils.contexts.
nullcontext
(enter_result=None)[source]¶ 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() with cm:
# Perform operation, using optional_cm if condition is True