Skip to content

Commit

Permalink
Fix type order relevance for union wrapping 2 types (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
george-zubrienko authored Jun 13, 2023
1 parent b2dd567 commit 2ca1d01
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
2 changes: 1 addition & 1 deletion dataclasses_json/mm.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def schema(cls, mixin, infer_missing):
options['allow_none'] = True
if len(type_.__args__) == 2:
# Union[str, int, None] is optional too, but it has more than 1 typed field.
type_ = type_.__args__[0]
type_ = [tp for tp in type_.__args__ if tp is not type(None)][0]

if metadata.letter_case is not None:
options['data_key'] = metadata.letter_case(field.name)
Expand Down
48 changes: 47 additions & 1 deletion tests/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,47 @@ class C9:
f1: List[Union[Aux1, Aux2]]


try:
@dataclass_json
@dataclass
class C10:
"""
Use py3.10+ pipe notation for optionals
Check if passing None as the first type option doesn't break type resolution
Instantiate with None default so NoneType is returned for runtime field value type.
"""
f1: None | str = None
except TypeError:
@dataclass_json
@dataclass
class C10:
"""
Replace test case on versions prior to 3.10
"""
f1: Union[None, str] = None


try:
@dataclass_json
@dataclass
class C11:
"""
Use py3.10+ pipe notation for optionals
Check if passing None as the second type option doesn't break type resolution
Instantiate with None default so NoneType is returned for runtime field value type.
"""
f1: str | None = None
except TypeError:
@dataclass_json
@dataclass
class C11:
"""
Replace test case on versions prior to 3.10
"""
f1: Union[str, None] = None

params = [
(C1(f1=12), {"f1": 12}, '{"f1": 12}'),
(C1(f1="str1"), {"f1": "str1"}, '{"f1": "str1"}'),
Expand Down Expand Up @@ -106,7 +147,12 @@ class C9:

(C9([Aux1(12), Aux2("str3")]),
{"f1": [{"f1": 12, "__type": "Aux1"}, {"f1": "str3", "__type": "Aux2"}]},
'{"f1": [{"f1": 12, "__type": "Aux1"}, {"f1": "str3", "__type": "Aux2"}]}')
'{"f1": [{"f1": 12, "__type": "Aux1"}, {"f1": "str3", "__type": "Aux2"}]}'),

(C10(f1=None), {"f1": None}, '{"f1": null}'),
(C10(f1='str1'), {"f1": 'str1'}, '{"f1": "str1"}'),

(C11(f1=None), {"f1": None}, '{"f1": null}')
]


Expand Down

0 comments on commit 2ca1d01

Please sign in to comment.