_resources.py 783 B

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