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
6 changes: 4 additions & 2 deletions serde/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@
class UnionCacheKey:
union: Hashable
tagging: Tagging
# Union[int, str] == Union[str, int], but the generated code depends on the order.
order: str


def init(debug: bool = False) -> None:
Expand Down Expand Up @@ -179,7 +181,7 @@ def _get_union_class(self, cls: type[Any]) -> type[Any] | None:
the class and store it in the cache.
"""
union_cls, tagging = _extract_from_with_tagging(cls)
cache_key = UnionCacheKey(union=union_cls, tagging=tagging)
cache_key = UnionCacheKey(union=union_cls, tagging=tagging, order=repr(union_cls))
wrapper = self.classes.get(cache_key)
return wrapper or self._generate_union_class(cls)

Expand All @@ -191,7 +193,7 @@ def _generate_union_class(self, cls: type[Any]) -> type[Any]:
import serde

union_cls, tagging = _extract_from_with_tagging(cls)
cache_key = UnionCacheKey(union=union_cls, tagging=tagging)
cache_key = UnionCacheKey(union=union_cls, tagging=tagging, order=repr(union_cls))
class_name = union_func_name(
f"{tagging.produce_unique_class_name()}Union", list(type_args(union_cls))
)
Expand Down
26 changes: 26 additions & 0 deletions tests/test_union.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import dataclasses
import logging
import uuid
from dataclasses import dataclass
Expand Down Expand Up @@ -834,6 +835,31 @@ class Foo:
assert f == from_json(Foo, s)


def test_union_directly_with_different_ordering() -> None:
@dataclass
class Foo:
v: int

@dataclass
class Bar:
w: str

bar = Bar("bar")
for union in (Union[Foo, Bar], Union[Bar, Foo]):
assert to_json(bar, cls=union) == '{"Bar":{"w":"bar"}}'
assert from_json(union, '{"Bar":{"w":"bar"}}') == bar

for typ in (list[Union[Foo, Bar]], list[Union[Bar, Foo]]):
assert from_json(typ, '[{"Bar":{"w":"bar"}}]') == [bar]


def test_union_directly_with_same_named_classes() -> None:
IntFoo = dataclasses.make_dataclass("Foo", [("v", int)])
StrFoo = dataclasses.make_dataclass("Foo", [("v", str)])
assert from_json(Union[IntFoo, int], '{"Foo":{"v":1}}') == IntFoo(1)
assert type(from_json(Union[StrFoo, int], '{"Foo":{"v":"a"}}')) is StrFoo


def test_union_internal_tagging_for_non_dataclass() -> None:
@serde
class Bar:
Expand Down
Loading