Total Complexity | 7 |
Total Lines | 53 |
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 Callable, Any, Optional, TYPE_CHECKING, Dict |
||
7 | |||
8 | from .types import T, MISSING |
||
9 | |||
10 | if TYPE_CHECKING: |
||
11 | from pincer.client import Client |
||
12 | |||
13 | |||
14 | def construct_client_dict(client: Client, data: Dict[...]): |
||
15 | """ |
||
16 | Constructs a proper kwargs dict with the client props. |
||
17 | """ |
||
18 | |||
19 | return { |
||
20 | **data, |
||
21 | "_client": client, |
||
22 | "_http": client.http |
||
23 | } |
||
24 | |||
25 | |||
26 | def convert( |
||
27 | value: Any, |
||
28 | factory: Callable[[Any], T], |
||
29 | check: Optional[type] = None, |
||
30 | client: Optional[Client] = None |
||
31 | ) -> T: |
||
32 | """ |
||
33 | Convert a value to T if its not MISSING. |
||
34 | """ |
||
35 | |||
36 | def handle_factory() -> T: |
||
37 | def fin_fac(v: Any): |
||
38 | if check is not None and isinstance(v, check): |
||
39 | return v |
||
40 | |||
41 | if client is None: |
||
42 | return factory(v) |
||
43 | |||
44 | return factory(construct_client_dict(client, v)) |
||
45 | |||
46 | return ( |
||
47 | list(map(fin_fac, value)) |
||
48 | if isinstance(value, list) |
||
49 | else fin_fac(value) |
||
50 | ) |
||
51 | |||
52 | return MISSING if value is MISSING else handle_factory() |
||
53 |