Select a model with a discriminator
An untagged union may try several candidate models before deciding what the input means. A discriminator makes the decision explicit: a literal tag selects one branch, and only that branch's fields are validated.
This works well for events, commands and configuration variants. Give each branch a unique tag and preserve it when serializing. An unknown tag is an error, not a reason to guess a branch. Fields valid for a different variant must not accidentally make an invalid event appear acceptable.
from typing import Annotated, Literal
from pydantic import BaseModel, Field
from pydantic import TypeAdapter
class Add(BaseModel):
kind: Literal["add"]
amount: int
Event = Annotated[Add, Field()]
print(TypeAdapter(Event).validate_python(
{"kind": "add", "amount": "3"}))Your task
Implement event_value(raw) validating a discriminated union: Add(kind="add", amount:int) or Remove(kind="remove", key:str). Return the amount or key. Reject unknown tags and missing branch fields.
The explanation opens here once every check passes.