To create an asynchronous Python context manager, including MyPy type hints, in Python 3.10, add these imports:
from __future__ import annotations
from types import TracebackType
from typing import TypeThen add these functions:
def __enter__(self) -> None:
# This class only implements an async context manager.
raise NotImplementedError("Use 'async with' instead.")
def __exit__(
self, type: Type[BaseException], value: BaseException, traceback: TracebackType
) -> None:
# __exit__ should exist in pair with __enter__ but never be executed.
raise NotImplementedError("Use 'async with' instead.")
async def __aenter__(self) -> <class type>:
# Do here whatever necessary to be done when the context manager starts. And then:
return self
async def __aexit__(
self, type: Type[BaseException], value: BaseException, traceback: TracebackType
) -> None:
# Do here whatever necessary to be done when the context manager ends. No return statement needed.If a synchronous context manager is needed as well, implement the __enter__ and __exit__ functions.