From fff34f691b92fdd5df05a95ed3c297b469ccf4f0 Mon Sep 17 00:00:00 2001 From: Martin Date: Thu, 16 Feb 2023 22:10:18 +0300 Subject: [PATCH] Extend types in record to handle "..." and "bool | None" etc. --- funml/utils.py | 9 +++++++-- tests/test_records.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/funml/utils.py b/funml/utils.py index a9c8d1e..7a59105 100644 --- a/funml/utils.py +++ b/funml/utils.py @@ -7,7 +7,7 @@ import types import typing import random -from typing import Any, Dict, Tuple, List, Set +from typing import Any, Dict, Tuple, List, Set, Union _compound_type_regex = re.compile(r"tuple|list|set|dict") @@ -22,6 +22,7 @@ "Dict": Dict, "Set": Set, "List": List, + "Union": Union, } @@ -32,7 +33,7 @@ def is_type(value: Any, cls: Any) -> bool: Also subscriptable types are not really being checked well """ _type = cls - if _type in (Any,): + if _type in (Any, ...): return True if isinstance(_type, typing._SpecialForm): @@ -233,6 +234,10 @@ def _to_generic(annotation: str) -> str: This is just for compatibility when it comes to python < 3.10 """ + union_args = annotation.split("|") + if len(union_args) > 1: + annotation = f"Union[{','.join(union_args)}]" + return _compound_type_regex.sub( lambda v: _compound_type_generic_type_map[v.string[v.start() : v.end()]], annotation, diff --git a/tests/test_records.py b/tests/test_records.py index 7b58dc1..3e4ff48 100644 --- a/tests/test_records.py +++ b/tests/test_records.py @@ -120,24 +120,32 @@ class Department: juniors: List[str] locations: tuple[str, ...] misc: dict[str, Any] + is_active: bool | None + description: ... security_dept = Department( seniors=["Joe", "Jane"], juniors=["Herbert", "Leo"], locations=("Kasasa", "Bujumbura", "Bugahya"), misc={"short_name": "ScDept"}, + is_active=False, + description="security", ) it_dept = Department( seniors=["Paul"], juniors=["Perry"], locations=("Kampala", "Cairo"), misc={"name": "IT Department"}, + is_active=True, + description="it", ) hr_dept = Department( seniors=["Stella", "Isingoma"], juniors=["Peter"], locations=("Katanga",), misc={"short_name": "HRDept"}, + is_active=False, + description=4, ) another_security_dept = Department( @@ -145,18 +153,24 @@ class Department: juniors=["Herbert", "Leo"], locations=("Kasasa", "Bujumbura", "Bugahya"), misc={"short_name": "ScDept"}, + is_active=False, + description="security", ) another_it_dept = Department( seniors=["Paul"], juniors=["Perry"], locations=("Kampala", "Cairo"), misc={"name": "IT Department"}, + is_active=True, + description="it", ) another_hr_dept = Department( seniors=["Stella", "Isingoma"], juniors=["Peter"], locations=("Katanga",), misc={"short_name": "HRDept"}, + is_active=False, + description=4, ) assert security_dept == another_security_dept