Python 3.7+contextlibterm
contextlib.AbstractAsyncContextManager
protocols
The ABC for async context managers (the __aenter__/__aexit__ protocol).
Syntax
class C(contextlib.AbstractAsyncContextManager): ...
You rarely need to inherit from it: the subclass check is structural, based on __aenter__ and __aexit__ being present, so a suitable class already counts — the ABC mostly serves as a ready base (it supplies an __aenter__ returning self) and as a type annotation. That check only looks at method names, not at whether they are actually coroutines. Added in Python 3.7, and subscriptable for generics since 3.9.
Examples
import contextlib
class ACM:
async def __aenter__(self): return self
async def __aexit__(self, *a): return False
print(issubclass(ACM, contextlib.AbstractAsyncContextManager)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy