Passed
Pull Request — main (#248)
by
unknown
03:24
created

pincer.utils.conversion.convert()   B

Complexity

Conditions 7

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 31
rs 8
c 0
b 0
f 0
cc 7
nop 4
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 Any, Callable, Dict, List, Optional, Set, Union
14
15
16
<<<<<<< HEAD
0 ignored issues
show
introduced by
invalid syntax (<unknown>, line 16)
Loading history...
17
def construct_client_dict(client: Client, data: Dict) -> Dict:
18
=======
19
def construct_client_dict(client: Client, data: Dict[...]):
20
    # TODO: fix docs
21
    """
22
23
    Parameters
24
    ----------
25
    client
26
    data
27
28
    Returns
29
    -------
30
31
    """
32
>>>>>>> c636d240cbc1d61df9a46371005a9ce47c0cf0a3
33
    return {**data, "_client": client, "_http": client.http}
34
35
36
def convert(
37
    value: Any,
38
    factory: Callable[[Any], T],
39
    check: Optional[T] = None,
40
    client: Optional[Client] = None,
41
) -> T:
42
    """
43
    Parameters
44
    ----------
45
    value : Any
46
        The value that has to have its type converted.
47
    factory : Callable[[Any], T]
48
        The conversion factory/object to use.
49
    check : Optional[T]
50
        Skip conversion if ``value`` is already this type.
51
    client : Optional[:class:`~pincer.client.Client`]
52
        Reference to :class:`~pincer.client.Client`
53
    """
54
    def handle_factory() -> T:
55
        if check is not None and isinstance(value, check):
56
            return value
57
58
        try:
59
            if client and "_client" in getfullargspec(factory).args:
60
                return factory(construct_client_dict(client, value))
61
        except TypeError:  # Building type/has no signature
62
            pass
63
64
        return factory(value)
65
66
    return MISSING if value is MISSING else handle_factory()
67
68
def remove_none(obj: Union[List, Dict, Set]) -> Union[List, Dict, Set]:
69
    if isinstance(obj, list):
70
        while None in obj:
71
            obj.remove(None)
72
    elif isinstance(obj, set):
73
        obj.discard(None)
74
    elif isinstance(obj, dict):
75
        to_del = [k for k, v in obj.items() if None in {k, v}]
76
        for k in to_del:
77
            del obj[k]
78
    return obj