Skip to content

Commit 1cba1da

Browse files
authored
Merge pull request #441 from yukinarit/fix-union-any
Fix serializing union with Any
2 parents 76e919c + 596e7f6 commit 1cba1da

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

serde/core.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
is_list,
4545
is_literal,
4646
is_new_type_primitive,
47+
is_any,
4748
is_opt,
4849
is_set,
4950
is_tuple,
@@ -382,6 +383,8 @@ def is_instance(obj: Any, typ: Any) -> bool:
382383
return isinstance(obj, inner)
383384
else:
384385
return False
386+
elif is_any(typ):
387+
return True
385388
elif typ is Ellipsis:
386389
return True
387390
else:

tests/test_union.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import sys
33
from dataclasses import dataclass
44
from ipaddress import IPv4Address
5-
from typing import Dict, FrozenSet, Generic, List, NewType, Optional, Tuple, TypeVar, Union
5+
from typing import Dict, FrozenSet, Generic, List, NewType, Optional, Tuple, TypeVar, Union, Any
66
from uuid import UUID
77

88
import pytest
@@ -772,3 +772,21 @@ class Foo:
772772
a: Union[FrozenSet[int], int]
773773

774774
assert to_dict(Foo(frozenset({1}))) == {"a": {1}}
775+
776+
777+
def test_union_with_any():
778+
@dataclass
779+
class FooWithString:
780+
foo: str
781+
782+
@dataclass
783+
class BarWithDict:
784+
bar: Dict[str, Any]
785+
786+
@serde(tagging=Untagged)
787+
@dataclass
788+
class Class:
789+
foobars: List[Union[FooWithString, BarWithDict]]
790+
791+
c = Class([FooWithString("string"), BarWithDict({"key": "value"})])
792+
assert c == from_json(Class, to_json(c))

0 commit comments

Comments
 (0)