File: _get_origin.py

package info (click to toggle)
python-typish 1.9.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 324 kB
  • sloc: python: 1,632; makefile: 2
file content (39 lines) | stat: -rw-r--r-- 1,114 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import typing
from collections import deque, defaultdict
from collections.abc import Set
from inspect import isclass

from typish.functions._is_from_typing import is_from_typing


def get_origin(t: type) -> type:
    """
    Return the origin of the given (generic) type. For example, for
    ``t=List[str]``, the result would be ``list``.
    :param t: the type of which the origin is to be found.
    :return: the origin of ``t`` or ``t`` if it is not generic.
    """
    from typish.functions._get_simple_name import get_simple_name

    simple_name = get_simple_name(t)
    result = _type_per_alias.get(simple_name, None)
    if isclass(t) and not is_from_typing(t):
        # Get the origin in case of a parameterized generic.
        result = getattr(t, '__origin__', t)
    elif not result:
        result = getattr(typing, simple_name, t)
    return result


_type_per_alias = {
    'List': list,
    'Tuple': tuple,
    'Dict': dict,
    'Set': set,
    'FrozenSet': frozenset,
    'Deque': deque,
    'DefaultDict': defaultdict,
    'Type': type,
    'AbstractSet': Set,
    'Optional': typing.Union,
}