In Pydantic 2, why would you validate three payment event kinds as a discriminated union on a Literal tag rather than a plain union?
answer
- read the tag, try one member
- Field(discriminator=...)
- a Literal on every member
- union_tag_invalid versus union_tag_not_found
basics
~10 sA Pydantic 2 discriminated union reads one tag field, typed as a Literal on each member, and validates only the member it names, so selection is predictable, faster, and errors describe just that member.
solid answer
~40 sGive each event model a tag such as `kind: Literal['charge']`, `Literal['refund']`, `Literal['chargeback']`, and declare the field as `event: Charge | Refund | Chargeback = Field(discriminator='kind')`. Pydantic reads `kind`, validates only the matching member, and never tries the others, so a refund cannot be mistaken for a charge that happens to fit. An unknown tag fails with `union_tag_invalid`, a missing one with `union_tag_not_found`, and a bad member reports errors with the tag in the `loc`, such as `event.refund.amount`, instead of one error list per member. Every member must declare the tag as a `Literal`, or the schema fails to build. The generated JSON Schema also carries an OpenAPI `discriminator`. When members share no tag field, a callable `Discriminator` with a `Tag` on each member does the selection.
code
python · 37 linesfrom decimal import Decimal
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class Charge(BaseModel):
kind: Literal['charge']
amount: Decimal
card_last4: str
class Refund(BaseModel):
kind: Literal['refund']
amount: Decimal
original_charge_id: str
class Chargeback(BaseModel):
kind: Literal['chargeback']
amount: Decimal
dispute_reason: str
class Envelope(BaseModel):
event: Charge | Refund | Chargeback = Field(discriminator='kind')
payload = {'event': {'kind': 'refund', 'amount': '12.50', 'original_charge_id': 'ch_1'}}
print(Envelope.model_validate(payload))
#> event=Refund(kind='refund', amount=Decimal('12.50'), original_charge_id='ch_1')
try:
Envelope.model_validate({'event': {'kind': 'payout', 'amount': '1'}})
except ValidationError as exc:
print(exc.errors()[0]['type'])
#> union_tag_invalidgo deeper
Recall the shape: a Literal tag on each model and Field(discriminator='kind') on the union field, so the tag picks the model.
Explain that only the selected member is validated, and name the two tag errors, union_tag_invalid and union_tag_not_found.
Argue from production: predictable selection, smaller error lists, faster validation, and a callable Discriminator with Tag when no common field exists.
Make tagged events a contract rule for producers: a required kind tag on every polymorphic payload saves every consumer from guessing.
## The problem with an untagged union of models A payment-events endpoint receives three kinds of event: charges, refunds and chargebacks. Typed as a plain union, `Charge | Refund | Chargeback`, Pydantic 2 uses **smart mode**: it validates the input against every member and picks the best-scoring success. That has three costs: - **Ambiguity.** Models that share fields, such as `amount`, can each accept the same payload, because unknown keys are ignored by default, and the winner depends on a scoring algorithm the documentation reserves the right to change. - **Noise.** When nothing matches, the error contains every member's errors, which for nested or recursive models multiplies fast. - **Cost.** Every member is attempted on every input. ## Declaring a discriminated union A **discriminated union**, also called a tagged union, names one field whose value selects the member: 1. Give every member the tag field, typed as a `Literal`: `kind: Literal['charge']` on `Charge`, `kind: Literal['refund']` on `Refund`. A member may accept several tag values, such as `Literal['chargeback', 'dispute']`. 2. Declare the union field with `Field(discriminator='kind')`, or regroup it with the annotated pattern: `Annotated[Charge | Refund | Chargeback, Field(discriminator='kind')]`. 3. Validate as usual, through the model or, for a bare union, a `TypeAdapter` built on that annotated type. ## What validation does with the tag When input arrives, Pydantic reads the tag from the dict or object, looks up the one member that declares that value, and validates against that member alone. No other member is tried, so there is no scoring and no guessing, and a payload whose `kind` is `'refund'` can only ever become a `Refund`. ## The errors you get | Situation | Error type | Example `loc` | |---|---|---| | Tag value matches no member | `union_tag_invalid` | `event` | | Tag cannot be extracted from the input | `union_tag_not_found` | `event` | | Tag matches, member fails | the member's own type, such as `missing` | `event.refund.original_charge_id` | The third row is the practical win: the error path names the selected member by its tag, and only that member's errors appear. ## When there is no common tag field Sometimes members share no field, or the union mixes a model with a plain type. A **callable `Discriminator`** handles that: you write a function that inspects the input and returns a tag, and mark each member with `Tag('...')` inside `Annotated`. Two rules apply: - The function must handle both dicts and model instances, because Pydantic also calls it during serialization, where it receives the model. - Returning `None` means no tag was found, which raises `union_tag_not_found`. A `Discriminator` can also take `custom_error_type`, `custom_error_message` and `custom_error_context` to shape that error. ## Validating a batch of events Feeds rarely send one event at a time. Because the discriminator travels with the annotated type, you can define it once and reuse it anywhere a type is accepted: 1. Name it: `Event = Annotated[Charge | Refund | Chargeback, Field(discriminator='kind')]`. 2. Use it as an element type, such as `events: list[Event]` on a batch model, or build `TypeAdapter(list[Event])` when there is no wrapper model. 3. Validate the raw body with `validate_json` on the adapter, so each element is routed by its own tag and an error's `loc` starts with the element index, then the tag. One bad element then produces errors for that element's selected member only, which keeps a 500-event batch error readable. ## Rules and limits - Every member must declare the tag field, and it must be a `Literal`; otherwise Pydantic raises a usage error when the schema is built, not at request time. - A `before`, `wrap` or `plain` validator on the tag field is not allowed, because it could change the value used to pick the member. - A field takes one discriminator; to combine two, nest discriminated unions through nested `Annotated` types, such as a `kind` tag outside and a `card_network` tag inside. - The generated JSON Schema includes the OpenAPI `discriminator` object, so documentation tools can show the mapping. Pydantic's own documentation recommends discriminated unions over untagged ones for being both more performant and more predictable. In an interview, the strongest answer ties that to the feed: the producer already says which kind of event it sent, so let the tag decide instead of letting a scorer infer it.
- In Pydantic 2, how do you validate a bare list of tagged events without wrapping them in a model?Build the annotated union once, `Event = Annotated[Charge | Refund | Chargeback, Field(discriminator='kind')]`, and validate with `TypeAdapter(list[Event])`, calling `validate_python` or `validate_json`. The discriminator travels with the annotated type, so each element is routed by its own tag.
- In Pydantic 2, what must a callable Discriminator handle besides dict input?Model instances. Pydantic calls the discriminator function during serialization too, where the input is usually the model, so it should read the tag with attribute access as well as dict lookup. Skipping that leads to warnings during serialization at best and runtime errors at worst.
A mailroom that reads the department code on each envelope and delivers it to that one desk, instead of opening every letter and trying it against each department's forms; an envelope with an unknown code goes back to the sender.
- A discriminated union tries every member and then filters them by the tag.
- The tag field can be a plain str with a default value.
- An unknown tag silently falls back to smart union matching.
- Discriminated unions only work for top-level models, not inside lists.
- A before validator on the tag field is a good place to normalise its case.