_resources.py 900 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. from __future__ import annotations
  2. import sys
  3. from abc import ABCMeta, abstractmethod
  4. from types import TracebackType
  5. from typing import TypeVar
  6. if sys.version_info >= (3, 11):
  7. from typing import Self
  8. else:
  9. from typing_extensions import Self
  10. T = TypeVar("T")
  11. class AsyncResource(metaclass=ABCMeta):
  12. """
  13. Abstract base class for all closeable asynchronous resources.
  14. Works as an asynchronous context manager which returns the instance itself on enter,
  15. and calls :meth:`aclose` on exit.
  16. """
  17. __slots__ = ()
  18. async def __aenter__(self) -> Self:
  19. return self
  20. async def __aexit__(
  21. self,
  22. exc_type: type[BaseException] | None,
  23. exc_val: BaseException | None,
  24. exc_tb: TracebackType | None,
  25. ) -> None:
  26. await self.aclose()
  27. @abstractmethod
  28. async def aclose(self) -> None:
  29. """Close the resource."""