Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Models and Types

Unions, Literals and Discriminated Unions

Accept several types with unions, restrict values with Literal, understand smart mode matching, and use discriminated unions for fast, clear validation of tagged data.

Sometimes a field can hold one of several shapes: an ID that is an int or a str, a payment that is a card or a bank transfer, an event that is a click or a key press. Python expresses this with a union (A | B). This lesson shows how Pydantic chooses between the members, how Literal restricts values to exact choices, and how a discriminated union makes tagged data fast and unambiguous.

Plain unions and smart mode

When a field is int | str, Pydantic must decide which member to use. Its default smart mode works like this: first look for a member the input matches exactly (without conversion); if none, try conversions and pick the best match. This keeps "abc" as a string and 5 as an int, instead of blindly using the first member.

Python Smart mode picks the best match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The exact type wins when there is one (5 stays an int, "abc" stays a string). "42" is a string, so it is also kept as a string, because the input already matched str exactly. If you want to try members strictly in order, use Field(union_mode="left_to_right").

Literal: exact allowed values

Literal from typing says the value must be one of a few exact constants. It is a lightweight alternative to an Enum and works for strings, ints, bools and None.

Python Literal choices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Literals are checked exactly and case-sensitively: "get" is rejected. They are also the key ingredient of discriminated unions, below.

Unions of models

Unions work with models too. In smart mode Pydantic tries each model and prefers the one that validates without errors and matches the most fields.

Python Union of two models

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This works, but two things are unsatisfying. When data matches neither type, the error lists problems for every member, which is noisy; and if the shapes overlap, a wrong member might be chosen. A discriminator fixes both.

Discriminated unions

Add a field with a fixed Literal value to each model: the tag (or discriminator). Then tell the union which field to look at with Field(discriminator="..."). Pydantic reads the tag first and validates only that model.

Python A tagged union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The error messages are short and precise: for the first event only the missing y is reported, and for the unknown tag "tap" you are told which tags are allowed. Without a discriminator you would get a wall of errors for every union member.

flowchart LR
    IN["Input dict"] --> T{"Read tag<br/>kind"}
    T -->|click| A["Validate as Click"]
    T -->|key| B["Validate as KeyPress"]
    T -->|scroll| C["Validate as Scroll"]
    T -->|other| E["Error: invalid tag"]

One lookup chooses the model; the others are never tried.

Discriminated unions are also faster, since only one branch runs. Use them whenever your data has a type tag, which is very common in JSON APIs ("type": "card", "event": "created").

The discriminator field name in the JSON can differ from the Python name if you use aliases. For tagged data that is not a dict with a single field, Pydantic also supports callable discriminators with Discriminator and Tag; see the reference documentation for that advanced form.

Optional is a union with None

Remember that str | None is simply a union. It follows the same rules, so None is kept as None and everything else must be a valid string. For the optional-field rules see Optional Fields and Defaults.

Choosing between Literal, Enum and a union

You have Use
A few fixed constants, no behaviour Literal["a", "b"]
Named constants you also use in code (Role.ADMIN) Enum (see Field Types)
Several shapes with a type tag discriminated union of models
Several unrelated types, no tag plain union (smart mode)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In smart mode, which member does Pydantic prefer for the input 5 with the annotation int | str?

    Smart mode looks for an exact type match first. 5 is an int, so it stays an int.
  2. 2. What does Literal['GET', 'POST'] do with the input 'get'?

    Literal compares against the exact listed values.
  3. 3. Why use a discriminated union instead of a plain union of models?

    The tag selects one branch directly, so errors are short and no other models are tried.
  4. 4. Which pieces make up a discriminated union?

    Each member has a Literal-typed tag field, and the union is annotated with Field(discriminator=...).

Summary

  • A union (A | B) lets a field accept several types; smart mode prefers an exact match, then the best conversion.
  • Literal restricts a field to exact constants, case-sensitively.
  • Unions of models work, but errors can be noisy and shapes can be ambiguous.
  • A discriminated union (Literal tag field in each model plus Field(discriminator=...)) validates only the matching model, with clear errors and better speed.
  • X | None is just a union with None.

Next: Model Inheritance and Generic Models