-
Notifications
You must be signed in to change notification settings - Fork 10
Description
Sometimes it would be good to store a type identifier in union fields. This would be especially true for sparsely populated data and unions containing str
(described below).
Consider:
import typing
import attr
import desert
@attr.dataclass
class A:
color: str
@attr.dataclass
class B:
color: str
@attr.dataclass
class C:
things: typing.List[typing.Union[A, B]]
We then create some instances:
instances = C(
things=[
A(color='red'),
A(color='green'),
B(color='blue'),
],
)
Theoretically that would serialize to (it doesn't seem to so there will presumably be another issue report):
{"things": [{"color": "red"}, {"color": "green"}, {"color": "blue"}]}
Which leaves us wondering what any of the things are.
On the flip side, if we take an example in the tests where there is a field t.Union[int, str]
then adjust it to include a custom class after str
such as t.Union[int, str, MyClass]
then str
will 'always' work and MyClass
instances will be serialized to a str
such as 'MyClass()'
(well, for an attrs
class with such a repr()
anyways).
tl;dr, marshmallow-union
has some pretty significant limitations. I got myself confused and started creating a solution over in marshmallow-polyfield
Bachmann1234/marshmallow-polyfield#34 which would introduce an extra layer to the serialization and include a string to designate the type of that element. No more guessing.
{
"things": [
{
"type": "A",
"value": {
"color": "red",
}
},
{
"type": "A",
"value": {
"color": "green",
}
},
{
"type": "B",
"value": {
"color": "blue",
}
}
]
}
Perhaps desert
is interested in using marshmallow-polyfield
for that feature? Perhaps desert
would rather the feature be added to marshmallow-union
?
In the mean time I'll try to find time to work my way through reporting and possibly fixing some other issues.