Passed
Push — main ( 75eeb1...02999c )
by Yohann
01:29
created

pincer.utils.conversion.convert()   B

Complexity

Conditions 6

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 26
rs 8.6166
c 0
b 0
f 0
cc 6
nop 4
1
# -*- coding: utf-8 -*-
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# MIT License
3
#
4
# Copyright (c) 2021 Pincer
5
#
6
# Permission is hereby granted, free of charge, to any person obtaining
7
# a copy of this software and associated documentation files
8
# (the "Software"), to deal in the Software without restriction,
9
# including without limitation the rights to use, copy, modify, merge,
10
# publish, distribute, sublicense, and/or sell copies of the Software,
11
# and to permit persons to whom the Software is furnished to do so,
12
# subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
from __future__ import annotations
25
26
from typing import Callable, Any, Optional, TYPE_CHECKING
27
from .types import T, MISSING
28
29
if TYPE_CHECKING:
30
    from pincer.client import Client
31
32
33
def convert(
34
        value: Any,
35
        factory: Callable[[Any], T],
36
        check: Optional[type] = None,
37
        client: Optional[Client] = None
38
) -> T:
39
    """
40
    Convert a value to T if its not MISSING.
41
    """
42
    def handle_factory() -> T:
43
        def fin_fac(v: Any):
44
            if check is not None and isinstance(v, check):
45
                return v
46
47
            if client is None:
48
                return factory(v)
49
50
            return factory(v | {"_client": client, "_http": client.http})
51
52
        return (
53
            list(map(fin_fac, value))
54
            if isinstance(value, list)
55
            else fin_fac(value)
56
        )
57
58
    return MISSING if value is MISSING else handle_factory()
59