Skip to content

Commit

Permalink
Improve normalize_type_hint
Browse files Browse the repository at this point in the history
  • Loading branch information
thombashi committed Oct 2, 2021
1 parent e703f86 commit c86f15c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
27 changes: 14 additions & 13 deletions dataproperty/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,33 +26,34 @@
FloatType = Union[Type[Decimal], Type[float]]

_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,
"dictionary": Dictionary,
"inf": Infinity,
"infinity": Infinity,
"int": Integer,
"integer": Integer,
"ip": IpAddress,
"ipaddr": IpAddress,
"ipaddress": IpAddress,
"list": List,
"nan": Nan,
"none": NoneType,
"nullstr": NullString,
"nullstring": NullString,
"realnumber": RealNumber,
"str": String,
"string": String,
}


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

if isinstance(type_hint, str):
return _type_hint_map[type_hint.casefold()]
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

return type_hint
raise ValueError(f"unknown typehint: {type_hint}")
4 changes: 4 additions & 0 deletions test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class Test_normalize_type_hint:
["inf", Infinity],
["infinity", Infinity],
["int", Integer],
["int ", Integer],
["int_", Integer],
["integer", Integer],
["ip", IpAddress],
["ipaddr", IpAddress],
Expand All @@ -41,10 +43,12 @@ class Test_normalize_type_hint:
["none", NoneType],
["nullstr", NullString],
["nullstring", NullString],
["float", RealNumber],
["realnumber", RealNumber],
["str", String],
["string", String],
["", None],
[None, None],
],
)
def test_normal(self, value, expected):
Expand Down

0 comments on commit c86f15c

Please sign in to comment.