typish.functions._get_alias.get_alias()   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nop 1
dl 19
loc 19
rs 9.9
c 0
b 0
f 0
1
import typing
2
from functools import lru_cache
3
4
from typish.functions._is_from_typing import is_from_typing
5
6
from typish._types import T
7
8
9 View Code Duplication
@lru_cache()
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10
def get_alias(cls: T) -> typing.Optional[T]:
11
    """
12
    Return the alias from the ``typing`` module for ``cls``. For example, for
13
    ``cls=list``, the result would be ``typing.List``. If ``cls`` is
14
    parameterized (>=3.9), then a parameterized ``typing`` equivalent is
15
    returned. If no alias exists for ``cls``, then ``None`` is returned.
16
    If ``cls`` already is from ``typing`` it is returned as is.
17
    :param cls: the type for which the ``typing`` equivalent is to be found.
18
    :return: the alias from ``typing``.
19
    """
20
    if is_from_typing(cls):
21
        return cls
22
    alias = _alias_per_type.get(cls.__name__, None)
23
    if alias:
24
        args = getattr(cls, '__args__', tuple())
25
        if args:
26
            alias = alias[args]
27
    return alias
28
29
30
_alias_per_type = {
31
    'list': typing.List,
32
    'tuple': typing.Tuple,
33
    'dict': typing.Dict,
34
    'set': typing.Set,
35
    'frozenset': typing.FrozenSet,
36
    'deque': typing.Deque,
37
    'defaultdict': typing.DefaultDict,
38
    'type': typing.Type,
39
    'Set': typing.AbstractSet,
40
}
41