diff --git a/serde/core.py b/serde/core.py index e33f9e19..524fa3b6 100644 --- a/serde/core.py +++ b/serde/core.py @@ -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: @@ -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) @@ -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)) ) diff --git a/tests/test_union.py b/tests/test_union.py index 7df46119..0c69f0d6 100644 --- a/tests/test_union.py +++ b/tests/test_union.py @@ -1,3 +1,4 @@ +import dataclasses import logging import uuid from dataclasses import dataclass @@ -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: