Skip to content

Commit

Permalink
fix: Fix deserialization of optional complex types with default=None
Browse files Browse the repository at this point in the history
  • Loading branch information
kmsquire committed Sep 1, 2022
1 parent 1f48c9c commit 2b3b7ae
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
11 changes: 4 additions & 7 deletions serde/de.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,14 +648,11 @@ def opt(self, arg: DeField) -> str:
if data.get("f") is not None else None'
"""
value = arg[0]
if has_default(arg):
return self.render(value)
if arg.iterbased:
exists = f'{arg.data} is not None'
else:
if arg.iterbased:
exists = f'{arg.data} is not None'
else:
exists = f'{arg.datavar}.get("{arg.conv_name()}") is not None'
return f'({self.render(value)}) if {exists} else None'
exists = f'{arg.datavar}.get("{arg.conv_name()}") is not None'
return f'({self.render(value)}) if {exists} else None'

def list(self, arg: DeField) -> str:
"""
Expand Down
23 changes: 23 additions & 0 deletions tests/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,29 @@ class A:
assert a_none == from_dict(A, to_dict(a_none, reuse_instances=True), reuse_instances=True)


def test_optional_complex_type_with_default():
for T, default in [
(IPv4Address, IPv4Address("127.0.0.1")),
(UUID, UUID("9c244009-c60d-452b-a378-b8afdc0c2d90")),
]:

@serde
class A:
id: Optional[T] = None

a = A(default)
assert a == from_dict(A, to_dict(a, reuse_instances=False), reuse_instances=False)
assert a == from_dict(A, to_dict(a, reuse_instances=True), reuse_instances=True)

a_none = A(None)
assert a_none == from_dict(A, to_dict(a_none, reuse_instances=False), reuse_instances=False)
assert a_none == from_dict(A, to_dict(a_none, reuse_instances=True), reuse_instances=True)

a_default = A()
assert a_default == from_dict(A, to_dict(a_default, reuse_instances=False), reuse_instances=False)
assert a_default == from_dict(A, to_dict(a_default, reuse_instances=True), reuse_instances=True)


def test_union_with_complex_types_in_containers():
@serde
class A:
Expand Down

0 comments on commit 2b3b7ae

Please sign in to comment.