From c86f15c6ead727394006b804ce0233a482b7c782 Mon Sep 17 00:00:00 2001 From: Tsuyoshi Hombashi Date: Sat, 2 Oct 2021 18:33:57 +0900 Subject: [PATCH] Improve normalize_type_hint --- dataproperty/typing.py | 27 ++++++++++++++------------- test/test_typing.py | 4 ++++ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/dataproperty/typing.py b/dataproperty/typing.py index 5162298..91c2f17 100644 --- a/dataproperty/typing.py +++ b/dataproperty/typing.py @@ -26,25 +26,21 @@ 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, } @@ -52,7 +48,12 @@ 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}") diff --git a/test/test_typing.py b/test/test_typing.py index 658df89..7ea2140 100644 --- a/test/test_typing.py +++ b/test/test_typing.py @@ -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], @@ -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):