Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.AsyncExitStack

Collects cleanup actions dynamically and unwinds them in reverse registration order on asynchronous scope exit.

Version: Python 3.14; repository image, production runtime not attested

Syntax

async with contextlib.AsyncExitStack() as stack:

Collects cleanup actions dynamically and unwinds them in reverse registration order on asynchronous scope exit.

Asynchronous cleanup must be registered through an asynchronous callback method; ordinary callbacks are also supported.

Build a dynamic LIFO stack for sync and async cleanup. enter_async_context awaits entry and registers exit; push_async_callback registers an awaitable cleanup without exception arguments. Ordinary callback accepts synchronous cleanup. On exit or explicit await aclose(), later registrations unwind first: second then first in the sample. Return values from stack.callback() and push_async_callback() cannot suppress exceptions. push_async_callback cannot suppress exceptions. push_async_exit receives the exception triple and may suppress by returning truthy. pop_all transfers registrations without running them.

import asyncio
async def main():
    from contextlib import AsyncExitStack
    order = []
    async def release(name):
        order.append(name)
    s = AsyncExitStack()
    s.callback(order.append, "first")
    s.push_async_callback(release, "second")
    await s.aclose()
    assert order == ["second", "first"]
asyncio.run(main())
import asyncio
async def main():
    from contextlib import AsyncExitStack
    seen = []
    async def suppress_key(typ, exc, tb):
        seen.append(typ)
        return typ is KeyError
    s = AsyncExitStack()
    s.push_async_exit(suppress_key)
    owner = s.pop_all()
    await s.aclose()
    assert not seen
    async with owner:
        raise KeyError
    assert seen == [KeyError]
asyncio.run(main())

Examples

import contextlib
import asyncio

async def release(label):
    print(label)

async def main():
    async with contextlib.AsyncExitStack() as stack:
        stack.callback(print, "first")
        stack.push_async_callback(release, "second")

asyncio.run(main())

Result

second
first

Build a dynamic LIFO stack for sync and async cleanup. enter_async_context awaits entry and registers exit; push_async_callback registers an awaitable cleanup without exception arguments. Ordinary callback accepts synchronous cleanup. On exit or explicit await aclose(), later registrations unwind first: second then first in the sample. Return values from stack.callback() and push_async_callback() cannot suppress exceptions. push_async_callback cannot suppress exceptions. push_async_exit receives the exception triple and may suppress by returning truthy. pop_all transfers registrations without running them.

Sources