You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There is inconsistent behavior in how a custom decoder is used depending on whether the field of the custom decoder has Optional type.
For optional fields which can be None, you are supposed to use the Optional[...] type. However, when doing so, it seems that custom decoders are always evaluated.
It should be noted that fields where the default value is None but no Optional[...] typing is present, a custom decoder will only be used if a non-None value is provided.
field a2 with Optional typing / default None / custom decoder
field a3 with Optional typing / default None
fromdataclassesimportdataclass, fieldfromdataclasses_jsonimportDataClassJsonMixin, config@dataclassclassX(DataClassJsonMixin):
# This works as expecteda1: A=field(default=None, metadata=config(decoder=A))
# This does not work as expecteda2: Optional[A] =field(default=None, metadata=config(decoder=A))
# This works as expecteda3: Optional[A] =field(default=None)
If I were to deserialize an empty dictionary I would expect to receive to nonetype values for a1 and a2, however this is the result:
I also agree that I would consider this to be a bug since it generates incorrect objects according to the user provided types - we are ignoring None values in our parsing which is surely not a consistent API.
Problem
There is inconsistent behavior in how a custom decoder is used depending on whether the field of the custom decoder has
Optional
type.For optional fields which can be None, you are supposed to use the
Optional[...]
type. However, when doing so, it seems that custom decoders are always evaluated.It should be noted that fields where the default value is None but no
Optional[...]
typing is present, a custom decoder will only be used if a non-None value is provided.Example
Given the following nested dataclass:
and top-level dataclass
X
with three fields:a1
with defaultNone
/ custom decodera2
withOptional
typing / defaultNone
/ custom decodera3
withOptional
typing / defaultNone
If I were to deserialize an empty dictionary I would expect to receive to nonetype values for
a1
anda2
, however this is the result:The text was updated successfully, but these errors were encountered: