1 from abc import ABCMeta, abstractmethod

2 from types import TracebackType

3 from typing import Optional, Type, TypeVar

4

5 T = TypeVar("T")

6

7

8 class AsyncResource(metaclass=ABCMeta):

9 """

10 Abstract base class for all closeable asynchronous resources.

11

12 Works as an asynchronous context manager which returns the instance itself on enter, and calls

13 :meth:`aclose` on exit.

14 """

15

16 async def __aenter__(self: T) -> T:

17 return self

18

19 async def __aexit__(

20 self,

21 exc_type: Optional[Type[BaseException]],

22 exc_val: Optional[BaseException],

23 exc_tb: Optional[TracebackType],

24 ) -> None:

25 await self.aclose()

26

27 @abstractmethod

28 async def aclose(self) -> None:

29 """Close the resource."""