On this page
  1. contextlib.AsyncExitStack
  2. Import
  3. Signature & Overview
  4. Methods & Attributes
  5. Usage
  6. Gotchas
  7. REPL Inspect

contextlib.AsyncExitStack

Prev: contextlib.asynccontextmanager | Up: contextlib | Next: contextlib.chdir
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.AsyncExitStack
Tags: #public #python3 #stdlib #contextlib


Import

import contextlib
from contextlib import AsyncExitStack

Signature & Overview

contextlib.AsyncExitStack()

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

Methods & Attributes

Usage

import asyncio
from contextlib import AsyncExitStack, asynccontextmanager

@asynccontextmanager
async def tag(name: str, log: list[str]):
    log.append(f"+{name}")
    try:
        yield name
    finally:
        log.append(f"-{name}")

async def main():
    log: list[str] = []
    async with AsyncExitStack() as stack:
        await stack.enter_async_context(tag("a", log))
        await stack.enter_async_context(tag("b", log))
    assert log == ["+a", "+b", "-b", "-a"]

asyncio.run(main())

Gotchas

REPL Inspect

from contextlib import AsyncExitStack
help(AsyncExitStack)

Linked from

Related notes