Skip to content

Commit

Permalink
Extend types in record to handle "..." and "bool | None" etc.
Browse files Browse the repository at this point in the history
  • Loading branch information
Tinitto committed Feb 16, 2023
1 parent 7f43d36 commit fff34f6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions funml/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -22,6 +22,7 @@
"Dict": Dict,
"Set": Set,
"List": List,
"Union": Union,
}


Expand All @@ -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):
Expand Down Expand Up @@ -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,
Expand Down
14 changes: 14 additions & 0 deletions tests/test_records.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,43 +120,57 @@ 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(
seniors=["Joe", "Jane"],
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
Expand Down

0 comments on commit fff34f6

Please sign in to comment.