Python 3.6+contextlibterm
contextlib.AbstractContextManager
protocols
The abstract base class of context managers (the __enter__/__exit__ protocol); any class with these methods is its virtual subclass.
Syntax
class C(contextlib.AbstractContextManager): ...
Inheriting is a convenience, not a requirement: issubclass succeeds for any class defining __enter__ and __exit__, so your own manager needs no base class at all. What subclassing buys you is a ready __enter__ that returns self, leaving only __exit__ to write, plus a clean name to use in type hints. Async managers are not covered here — they have their own AbstractAsyncContextManager.
Examples
import contextlib
class CM:
def __enter__(self): return self
def __exit__(self, *a): return False
print(issubclass(CM, contextlib.AbstractContextManager)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy