Explicit type specification for unions
See original GitHub issueSometimes 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 https://github.com/Bachmann1234/marshmallow-polyfield/pull/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.
Issue Analytics
- State:
- Created 4 years ago
- Comments:54 (23 by maintainers)

Top Related StackOverflow Question
Hi all, I’m new to this project 👋Very interested in seeing this issue (and #89) get resolved. I’ve tried both
dataclass-jsonandmarshmallow-dataclassand gotten pretty disappointed, so I’m hopingdesertcan be the production-grade dataclass serialization library I need for the projects I maintain. Thank you for all the hard work you all have put into this library 🙏I happened to come across a good writeup of the various options for explicit type specification for unions, courtesy of the
Serdelibrary that handles serialization in the Rust programming language: https://serde.rs/enum-representations.htmlI think supporting a choice of explicit representation (and if possible, compatibility with Serde for cross-language applications) would really set this library apart from the competition, and if that’s the direction chosen by the maintainers, I’d love to be part of that journey.
Eh let’s start with the latter, we can always add more stuff if we want to.