Python 3.7+contextlibfunction
contextlib.asynccontextmanager
managers
A decorator turning an async generator (with one yield) into an async context manager (3.7+).
Syntax
@contextlib.asynccontextmanager
The yield must happen exactly once: an exception raised inside the async with body is thrown back into the generator at the yield, so release code belongs in a finally block or it silently never runs on failure. The manager it produces is single-use — the object returned by one call cannot serve two async with statements, so call the function again. Since Python 3.10 the result also works as a decorator on async functions.
Examples
import contextlib, inspect
@contextlib.asynccontextmanager
async def cm():
yield 1
print(hasattr(cm(), '__aenter__')) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy