Tagged unions¶
didactic.api.TaggedUnion ¶
Bases: Model
Base class for discriminated unions of Model subclasses.
Subclassing forms
A union root declares the discriminator field name::
class Shape(dx.TaggedUnion, discriminator="kind"): ...
A variant extends the root and pins the discriminator to one Literal value, then declares its own fields::
class Circle(Shape):
kind: Literal["circle"]
radius: float
class Square(Shape):
kind: Literal["square"]
side: float
Dispatch happens at the root: Shape.model_validate({"kind": ...})
looks up the discriminator value in Shape.__variants__ and
constructs the corresponding variant.
Notes
Validation and serialisation on a variant work exactly like any
Model; there is no overhead at the variant
level. Only Shape.model_validate and Shape.model_validate_json
do the dispatch.
See Also
didactic.Model : the base class TaggedUnion extends.
model_validate
classmethod
¶
Dispatch on the discriminator and validate as the matched variant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
JsonObject
|
Mapping that includes the discriminator field. |
required |
Returns:
| Type | Description |
|---|---|
TaggedUnion
|
An instance of the matching variant subclass. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the discriminator field is missing or its value is unknown to the union. |