Skip to content

Instantly share code, notes, and snippets.

@wvreeven
Created October 24, 2022 12:52
Show Gist options
  • Select an option

  • Save wvreeven/1aa88436fd69e8c4864f26a02194f81c to your computer and use it in GitHub Desktop.

Select an option

Save wvreeven/1aa88436fd69e8c4864f26a02194f81c to your computer and use it in GitHub Desktop.

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 Type

Then 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment