Passed
Pull Request — main (#226)
by
unknown
01:32
created

pincer.utils.conversion   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 25
dl 0
loc 63
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A construct_client_dict() 0 14 1
B convert() 0 31 7
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 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
0 ignored issues
show
introduced by
Cannot import 'client' due to syntax error 'invalid syntax (<unknown>, line 354)'
Loading history...
13
    from typing import Dict, Callable, Any, Optional
14
15
16
def construct_client_dict(client: Client, data: Dict[...]):
17
    # TODO: fix docs
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
18
    """
19
20
    Parameters
21
    ----------
22
    client
23
    data
24
25
    Returns
26
    -------
27
28
    """
29
    return {**data, "_client": client, "_http": client.http}
30
31
32
def convert(
33
    value: Any,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
34
    factory: Callable[[Any], T],
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
35
    check: Optional[T] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
36
    client: Optional[Client] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
37
) -> T:
38
    """
39
    Parameters
40
    ----------
41
    Value : Any
42
        The value that has to have its type converted.
43
    Factory : Callable[[Any], T]
44
        The conversion factory/object to use.
45
    Check : Optional[T]
46
        Skip conversion if ``value`` is already this type.
47
    Client : Optional[:class:`~pincer.client.Client`]
48
        Reference to :class:`~pincer.client.Client`
49
    """
50
    def handle_factory() -> T:
51
        if check is not None and isinstance(value, check):
52
            return value
53
54
        try:
55
            if client and "_client" in getfullargspec(factory).args:
56
                return factory(construct_client_dict(client, value))
57
        except TypeError:  # Building type/has no signature
58
            pass
59
60
        return factory(value)
61
62
    return MISSING if value is MISSING else handle_factory()
63