Skip to content

Commit bf4ad13

Browse files
committed
fix: allow optional and union types to be marks as "stdlib"
Fixes and issue where nested simple types were spuriously marked as cyclic.
1 parent d2a699a commit bf4ad13

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

src/typelib/graph.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def get_type_graph(t: type) -> graphlib.TopologicalSorter[TypeNode]:
142142
qualname = inspection.qualname(child)
143143
*rest, refname = qualname.split(".", maxsplit=1)
144144
is_argument = var is not None
145-
module = getattr(child, "__module__", None)
145+
module = ".".join(rest) or getattr(child, "__module__", None)
146146
if module in (None, "__main__") and rest:
147147
module = rest[0]
148148
is_class = inspect.isclass(child)

src/typelib/py/inspection.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,13 @@ def isbuiltintype(
480480

481481
@compat.cache
482482
def isstdlibtype(obj: type) -> compat.TypeIs[type[STDLibtypeT]]:
483+
if isoptionaltype(obj):
484+
nargs = tp.get_args(obj)[:-1]
485+
return all(isstdlibtype(a) for a in nargs)
486+
if isuniontype(obj):
487+
args = tp.get_args(obj)
488+
return all(isstdlibtype(a) for a in args)
489+
483490
return (
484491
resolve_supertype(obj) in STDLIB_TYPES
485492
or resolve_supertype(type(obj)) in STDLIB_TYPES

tests/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import dataclasses
4+
import datetime
45
import enum
56
import typing
67

@@ -54,3 +55,10 @@ class TDict(typing.TypedDict):
5455

5556
class GivenEnum(enum.Enum):
5657
one = "one"
58+
59+
60+
@dataclasses.dataclass
61+
class UnionSTDLib:
62+
timestamp: datetime.datetime | None = None
63+
date_time: datetime.datetime | None = None
64+
intstr: int | str = 0

tests/unit/unmarshals/test_api.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,13 @@
142142
given_input="one",
143143
expected_output=models.GivenEnum.one,
144144
),
145+
union_std_lib=dict(
146+
given_type=models.UnionSTDLib,
147+
given_input={"timestamp": 0},
148+
expected_output=models.UnionSTDLib(
149+
timestamp=datetime.datetime.fromtimestamp(0, datetime.timezone.utc)
150+
),
151+
),
145152
)
146153
def test_unmarshal(given_type, given_input, expected_output):
147154
# When

0 commit comments

Comments
 (0)