Skip to content
This repository has been archived by the owner on Sep 9, 2024. It is now read-only.

Commit

Permalink
Handle None for optional Enums.
Browse files Browse the repository at this point in the history
  • Loading branch information
seandstewart committed Dec 15, 2021
1 parent 4487e25 commit 47dca6a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
2 changes: 2 additions & 0 deletions tests/test_serdes.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ class MemberInt:
{"members": [{"field": "string"}, {"field": 1}]},
),
(objects.SubTypic, objects.SubTypic(var="", sub=""), {"var": "", "sub": ""}),
(Optional[objects.FooNum], None, None),
(Optional[objects.FooNum], objects.FooNum.bar, objects.FooNum.bar.value),
],
)
def test_serde_serialize(t, obj, prim):
Expand Down
37 changes: 31 additions & 6 deletions typic/serde/ser.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,13 +253,38 @@ def _compile_enum_serializer(self, annotation: Annotation) -> SerializerT:
# If we can predict a single type the return the serializer for that
if len(ts) == 1:
t = ts.pop()
va = self.resolver.annotation(t, flags=annotation.serde.flags)
va = self.resolver.annotation(
t,
flags=annotation.serde.flags,
is_optional=annotation.optional,
is_strict=annotation.strict,
parameter=annotation.parameter,
default=annotation.parameter.default,
)
vser = self.factory(va)

def serializer(
o: enum.Enum, *, lazy: bool = False, name: util.ReprT = None, _vser=vser
):
return _vser(o.value, lazy=lazy, name=name)
if va.optional:

def serializer(
o: Optional[enum.Enum],
*,
lazy: bool = False,
name: util.ReprT = None,
_vser=vser,
):
if o is None:
return o
return _vser(o.value, lazy=lazy, name=name)

else:

def serializer(
o: enum.Enum,
*,
lazy: bool = False,
name: util.ReprT = None,
_vser=vser,
):
return _vser(o.value, lazy=lazy, name=name)

return cast(SerializerT, serializer)
# Else default to lazy serialization
Expand Down

0 comments on commit 47dca6a

Please sign in to comment.