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