Total Complexity | 6 |
Total Lines | 37 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | # Copyright Pincer 2021-Present |
||
|
|||
2 | # Full MIT License can be found in `LICENSE` at the project root. |
||
3 | |||
4 | from __future__ import annotations |
||
5 | |||
6 | from typing import Generic, TypeVar, TYPE_CHECKING |
||
7 | |||
8 | from pincer.utils import APIObject |
||
9 | |||
10 | if TYPE_CHECKING: |
||
11 | from typing import Any, Coroutine, List, Type, Generator, AsyncIterator |
||
12 | |||
13 | T = TypeVar('T') |
||
14 | |||
15 | |||
16 | class APIDataGen(Generic[T]): |
||
17 | |||
18 | def __init__( |
||
19 | self, |
||
20 | factory: Type[T], |
||
21 | request_func: Coroutine[Any, None, Any] |
||
22 | ): |
||
23 | |||
24 | self.fac = factory if isinstance(factory, APIObject) else factory.from_dict |
||
25 | self.request_func = request_func |
||
26 | |||
27 | async def __async(self) -> List[T]: |
||
28 | data = await self.request_func |
||
29 | return [self.fac(i) for i in data] |
||
30 | |||
31 | def __await__(self) -> Generator[Any, None, Any]: |
||
32 | return self.__async().__await__() |
||
33 | |||
34 | async def __aiter__(self) -> AsyncIterator[List[T]]: |
||
35 | for item in await self: |
||
36 | yield self.fac(item) |
||
37 |