typish.functions._get_origin.get_origin()   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 17
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nop 1
dl 17
loc 17
rs 9.95
c 0
b 0
f 0
1
import typing
2
from collections import deque, defaultdict
3
from collections.abc import Set
4
from inspect import isclass
5
6
from typish.functions._is_from_typing import is_from_typing
7
8
9 View Code Duplication
def get_origin(t: type) -> type:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10
    """
11
    Return the origin of the given (generic) type. For example, for
12
    ``t=List[str]``, the result would be ``list``.
13
    :param t: the type of which the origin is to be found.
14
    :return: the origin of ``t`` or ``t`` if it is not generic.
15
    """
16
    from typish.functions._get_simple_name import get_simple_name
17
18
    simple_name = get_simple_name(t)
19
    result = _type_per_alias.get(simple_name, None)
20
    if isclass(t) and not is_from_typing(t):
21
        # Get the origin in case of a parameterized generic.
22
        result = getattr(t, '__origin__', t)
23
    elif not result:
24
        result = getattr(typing, simple_name, t)
25
    return result
26
27
28
_type_per_alias = {
29
    'List': list,
30
    'Tuple': tuple,
31
    'Dict': dict,
32
    'Set': set,
33
    'FrozenSet': frozenset,
34
    'Deque': deque,
35
    'DefaultDict': defaultdict,
36
    'Type': type,
37
    'AbstractSet': Set,
38
    'Optional': typing.Union,
39
}
40