Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions serde/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def recursive(cls: type[Any] | Any) -> None:
recursive(args[0])
recursive(args[1])
elif is_pep695_type_alias(cls):
recursive(cls.__value__)
recursive(get_pep695_type_alias_value(cls))
else:
lst.add(cls)

Expand All @@ -415,7 +415,7 @@ def recursive(cls: TypeLike) -> None:
for arg in type_args(cls):
recursive(arg)
elif is_pep695_type_alias(cls):
recursive(cls.__value__)
recursive(get_pep695_type_alias_value(cls))
if is_dataclass(cls):
stack.append(cls)
if isinstance(cls, type):
Expand Down Expand Up @@ -461,7 +461,7 @@ def recursive(cls: type[Any] | Any) -> None:
for arg in type_args(cls):
recursive(arg)
elif is_pep695_type_alias(cls):
recursive(cls.__value__)
recursive(get_pep695_type_alias_value(cls))
if is_dataclass(cls):
stack.append(cls)
if isinstance(cls, type):
Expand Down Expand Up @@ -1056,7 +1056,22 @@ def is_pep695_type_alias(typ: Any) -> bool:
"""
Test if the type is of PEP695 type alias.
"""
return isinstance(typ, _PEP695_TYPES)
return isinstance(typ, _PEP695_TYPES) or isinstance(get_origin(typ), _PEP695_TYPES)


def get_pep695_type_alias_value(typ: Any) -> Any:
"""
Get the aliased type of PEP695 type alias, with type arguments applied for a generic alias.
"""
origin = get_origin(typ)
if origin is None:
return typ.__value__
value = origin.__value__
params = getattr(value, "__parameters__", ())
if not params:
return value
args = dict(zip(origin.__type_params__, get_args(typ), strict=True))
return value[tuple(args[p] for p in params)]


@cache
Expand Down
5 changes: 3 additions & 2 deletions serde/de.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
is_union,
is_variable_tuple,
is_pep695_type_alias,
get_pep695_type_alias_value,
iter_literals,
iter_types,
iter_unions,
Expand Down Expand Up @@ -565,7 +566,7 @@ def from_obj(
# A PEP 695 type alias (``type T = Foo | Bar``) is a TypeAliasType, not the
# aliased type itself, so unwrap it to recognize e.g. a union.
if is_pep695_type_alias(c):
c = c.__value__ # type: ignore[attr-defined]
c = get_pep695_type_alias_value(c)

# It is possible that the parser already generates the correct data type requested
# by the caller. Hence, it should be checked early to avoid doing anymore work.
Expand Down Expand Up @@ -1021,7 +1022,7 @@ def render(self, arg: DeField[Any]) -> str:
elif is_any(arg.type) or is_ellipsis(arg.type):
res = arg.data
elif is_pep695_type_alias(arg.type):
res = self.render(dataclasses.replace(arg, type=arg.type.__value__))
res = self.render(dataclasses.replace(arg, type=get_pep695_type_alias_value(arg.type)))
elif is_primitive(arg.type):
# For subclasses for primitives e.g. class FooStr(str), coercing is always enabled
res = self.primitive(arg, not is_primitive_subclass(arg.type))
Expand Down
5 changes: 3 additions & 2 deletions serde/se.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
is_union,
is_variable_tuple,
is_pep695_type_alias,
get_pep695_type_alias_value,
iter_types,
iter_unions,
type_args,
Expand Down Expand Up @@ -421,7 +422,7 @@ def serializable_to_obj(object: Any) -> Any:
# A PEP 695 type alias (``type T = Foo | Bar``) is a TypeAliasType, not
# the aliased type itself, so unwrap it to recognize e.g. a union.
if c is not None and is_pep695_type_alias(c):
c = c.__value__
c = get_pep695_type_alias_value(c)

# If a class in the argument is a non-dataclass class e.g. Union[Foo, Bar],
# pyserde generates a wrapper (de)serializable dataclass on the fly,
Expand Down Expand Up @@ -989,7 +990,7 @@ def render(self, arg: SeField[Any]) -> str:
arg.type = type_args(arg.type)[0]
res = self.render(arg)
elif is_pep695_type_alias(arg.type):
res = self.render(dataclasses.replace(arg, type=arg.type.__value__))
res = self.render(dataclasses.replace(arg, type=get_pep695_type_alias_value(arg.type)))
else:
raise SerdeError(f"Unsupported type: {typename(arg.type)}")

Expand Down
21 changes: 21 additions & 0 deletions tests/test_type_alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,27 @@ class Baz:
assert value == from_dict(BazClass, to_dict(value))


@pytest.mark.skipif(sys.version_info < (3, 12), reason=_PEP695_REASON)
def test_pep695_generic_type_alias() -> None:
ns: dict[str, object] = {"serde": serde}
exec(
"""
type Point[T] = tuple[T, T]
type Polygon[T] = tuple[Point[T], ...]

@serde
class Figure:
name: str
polygon: Polygon[float]
""",
ns,
)
FigureClass = typing.cast(type, ns["Figure"])

value = FigureClass("test", ((0.0, 0.0), (1.0, 1.73), (-1.0, 1.73)))
assert value == from_dict(FigureClass, to_dict(value))


@pytest.mark.skipif(sys.version_info < (3, 12), reason=_PEP695_REASON)
def test_pep695_type_alias_literal() -> None:
ns: dict[str, object] = {"serde": serde, "Literal": typing.Literal}
Expand Down
Loading