Passed
Push — main ( f2e2cb...8ba93a )
by
unknown
02:33
created

pincer.utils.conversion.convert()   B

Complexity

Conditions 6

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 27
rs 8.6166
c 0
b 0
f 0
cc 6
nop 4
1
# Copyright Pincer 2021-Present
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
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
0 ignored issues
show
Bug introduced by
The name client does not seem to exist in module pincer.
Loading history...
introduced by
Cannot import 'pincer.client' due to syntax error 'invalid syntax (<unknown>, line 344)'
Loading history...
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