AsyncExitStack Manages Async Cleanup Order

Enter async context managers dynamically with AsyncExitStack, register a callback, and watch cleanup run in reverse order after the block.

PythonResilience

Code

pythonsnippet
27 lines
import asyncio
from contextlib import AsyncExitStack, asynccontextmanager


@asynccontextmanager
async def connection(name: str):
    print("open:", name)
    try:
        yield name.upper()
    finally:
        print("close:", name)


async def main() -> None:
    async with AsyncExitStack() as stack:
        first = await stack.enter_async_context(connection("database"))
        second = await stack.enter_async_context(connection("cache"))
        stack.callback(print, "sync callback runs first")
        print("using:", first, second)

    print("stack closed")
    await stack.aclose()
    print("second close is a no-op")


if __name__ == "__main__":
    asyncio.run(main())

How it works

AsyncExitStack Manages Async Cleanup Order keeps everything in the functions connection and main.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. From asyncio it pulls AsyncExitStack, asynccontextmanager — the imports name exactly which library surface the snippet touches.

Watch out for

  • Plan for an install step: asyncio is a real dependency, resolved by the package manager.

Applying it

Entry signature: def connection(name: str)

The file announces its steps in the output: open:, close:, using:.

Running the file executes main, which drives connection in order.

Statements that matter

async with AsyncExitStack() as stack:
    first = await stack.enter_async_context(connection("database"))
    second = await stack.enter_async_context(connection("cache"))
    stack.callback(print, "sync callback runs first")
    print("using:", first, second)
async def connection(name: str):
    print("open:", name)
    try:
        yield name.upper()
    finally:
        print("close:", name)

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`asyncio` — install it with the package manager before running.