Total Complexity | 10 |
Total Lines | 54 |
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 dataclasses import is_dataclass |
||
7 | from inspect import getfullargspec |
||
8 | from typing import TYPE_CHECKING |
||
9 | |||
10 | from .types import T, MISSING |
||
11 | |||
12 | if TYPE_CHECKING: |
||
13 | from ..client import Client |
||
14 | from typing import Dict, Callable, Any, Optional |
||
15 | |||
16 | |||
17 | def construct_client_dict(client: Client, data: Dict[...]): |
||
18 | return { |
||
19 | **data, |
||
20 | "_client": client, |
||
21 | "_http": client.http |
||
22 | } |
||
23 | |||
24 | |||
25 | def convert( |
||
26 | value: Any, |
||
27 | factory: Callable[[Any], T], |
||
28 | check: Optional[T] = None, |
||
29 | client: Optional[Client] = None |
||
30 | ) -> T: |
||
31 | def handle_factory() -> T: |
||
32 | def fin_fac(v: Any): |
||
33 | if is_dataclass(v): |
||
34 | return |
||
35 | |||
36 | if check is not None and isinstance(v, check): |
||
37 | return v |
||
38 | |||
39 | try: |
||
40 | if client and "_client" in getfullargspec(factory).args: |
||
41 | return factory(construct_client_dict(client, v)) |
||
42 | except TypeError: # Building type/has no signature |
||
43 | pass |
||
44 | |||
45 | return factory(v) |
||
46 | |||
47 | return ( |
||
48 | list(map(fin_fac, value)) |
||
49 | if isinstance(value, list) |
||
50 | else fin_fac(value) |
||
51 | ) |
||
52 | |||
53 | return MISSING if value is MISSING else handle_factory() |
||
54 |