Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.asynccontextmanager

Converts an asynchronous generator function into a factory for asynchronous context managers.

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

Syntax

@contextlib.asynccontextmanager

Converts an asynchronous generator function into a factory for asynchronous context managers.

Yield exactly once; put cleanup in a finally block so that exceptions in the body still trigger it.

Decorate an async generator function to make an async context manager factory. Its one yield supplies the as value; code before it acquires and a finally after it can await cleanup. A body exception is thrown into the generator at the yield point. Re-raise caught errors to propagate them. The sample yields 8 and prints closed when it exits. Individual manager instances are single-use. Since 3.10 using one to decorate an async function creates a fresh generator for each decorated call.

import asyncio
async def main():
    from contextlib import asynccontextmanager
    events = []
    @asynccontextmanager
    async def cm():
        try:
            yield 4
        finally:
            await asyncio.sleep(0)
            events.append("closed")
    try:
        async with cm() as value:
            assert value == 4
            raise ValueError
    except ValueError:
        assert events == ["closed"]
asyncio.run(main())
import asyncio
async def main():
    from contextlib import asynccontextmanager
    seen = []
    @asynccontextmanager
    async def track():
        seen.append("in")
        yield
    @track()
    async def work():
        return 3
    assert await work() == await work() == 3 and len(seen) == 2
asyncio.run(main())

Examples

import contextlib
import asyncio

@contextlib.asynccontextmanager
async def scope():
    try:
        yield 8
    finally:
        print("closed")

async def main():
    async with scope() as item:
        print(item)

asyncio.run(main())

Result

8
closed

Decorate an async generator function to make an async context manager factory. Its one yield supplies the as value; code before it acquires and a finally after it can await cleanup. A body exception is thrown into the generator at the yield point. Re-raise caught errors to propagate them. The sample yields 8 and prints closed when it exits. Individual manager instances are single-use. Since 3.10 using one to decorate an async function creates a fresh generator for each decorated call.

Sources