File size: 1,403 Bytes
28bf99c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from datetime import datetime
from decimal import Decimal
from typing import Any, Callable, Mapping, Optional, Type, Union

from typepy import (
    Bool,
    DateTime,
    Dictionary,
    Infinity,
    Integer,
    IpAddress,
    List,
    Nan,
    NoneType,
    NullString,
    RealNumber,
    String,
    Typecode,
)
from typepy.type import AbstractType


TypeHint = Optional[Type[AbstractType]]
TransFunc = Callable[[Any], Any]
DateTimeFormatter = Callable[[datetime], str]

FloatType = Union[Type[Decimal], Type[float]]
StrictLevelMap = Mapping[Union[str, Typecode], int]
TypeValueMap = Mapping[Typecode, Union[float, Decimal, None]]

_type_hint_map = {
    # high frequently used types
    "int": Integer,
    "float": RealNumber,
    "realnumber": RealNumber,
    "str": String,
    # low frequently used types
    "bool": Bool,
    "datetime": DateTime,
    "dict": Dictionary,
    "inf": Infinity,
    "ip": IpAddress,
    "list": List,
    "nan": Nan,
    "none": NoneType,
    "nullstr": NullString,
}


def normalize_type_hint(type_hint: Union[str, TypeHint]) -> TypeHint:
    if not type_hint:
        return None

    if not isinstance(type_hint, str):
        return type_hint

    type_hint = type_hint.strip().casefold()
    for key, value in _type_hint_map.items():
        if type_hint.startswith(key):
            return value

    raise ValueError(f"unknown typehint: {type_hint}")