Closed malthe closed 4 years ago
I've been using a literal for this - for example
from dataclasses import dataclass, field
from typing import Literal, Union
import dacite
@dataclass
class B:
kind: Literal["x"] = "x"
@dataclass
class C:
kind: Literal["y"] = "y"
A = Union[B, C]
@dataclass
class _UnionHelper:
data: A
assert dacite.from_dict(_UnionHelper, {"data": {"kind": "x"}}).data == B()
This is somewhat similar to https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions which is where I got the idea from.
Hi @malthe - thank you for reporting this issue.
As @camerongraybill you should use Literal
here. It's a way to go :)
In Rust's serde library, enum representation can be untagged (as currently supported in dacite), but also internally and externally tagged.
That is, it would be useful to have a means of disambiguating a polymorphic type based not on structure, but a tagged value.
For example:
The library would be able to use "kind" as an internal tagging:
External tagging is probably harder to do without using annotations.