skip to content

In Pydantic 2, how does the default smart union mode choose a member, and when would you set union_mode='left_to_right' instead?

level: seniorimportance: should knowfreq 30%

answer

  1. best match, not first match
  2. exact beats strict beats lax
  3. models count valid fields set
  4. order matters only when asked

basics

~20 s

Smart mode, the Pydantic 2 default, picks the best match: for plain types an exact match first, then the leftmost strict, then the leftmost lax match. left_to_right takes the first member that validates, so order decides.

solid answer

~40 s

In Pydantic 2 a union defaults to `union_mode='smart'`. For plain types it tries members left to right, returns at once on an exact type match, and otherwise returns the leftmost member that would pass in strict mode, then the leftmost that passes in lax mode. So `ref: int | str` keeps `'1042'` as a string. For models, dataclasses and TypedDicts it first counts valid fields set, since 2.8, and uses exactness as the tiebreaker. `union_mode='left_to_right'`, set with `Field` on the union field, accepts the first member that validates, which is Pydantic 1's behaviour: the same field turns `'1042'` into `1042`. Use it when you need guaranteed order, because the smart algorithm may change between minor releases; for objects, prefer a discriminated union.

code

python · 15 lines
python
from pydantic import BaseModel, Field


class SmartRef(BaseModel):
    ref: int | str


class OrderedRef(BaseModel):
    ref: int | str = Field(union_mode='left_to_right')


print(SmartRef(ref='1042'))
#> ref='1042'
print(OrderedRef(ref='1042'))
#> ref=1042

go deeper

for a junior

Recall that a Pydantic 2 union picks the best-matching member by default, so int | str keeps the string '1042' a string.

for a middle

Explain the exactness ladder, exact then strict then lax, and how left to right mode differs by taking the first success.

for a senior

Diagnose a wrong-member result: the valid-fields-set metric for models since 2.8, extra keys ignored, and why a discriminator fixes it.

for a principal

Treat union mode as a stability decision: smart behaviour may shift between minor releases, so any union your correctness depends on needs a pinned rule.

## Why unions need a policy Every other Pydantic type requires the input to satisfy one schema. A **union** needs only one member to succeed, and in lax mode several often can: the string `'1042'` is a valid `str` and, after conversion, a valid `int`. Pydantic therefore needs a rule for which member wins and which errors to report when none does. Pydantic 2 offers three: **smart mode** (the default), **left to right mode**, and **discriminated unions**, which select a member by a tag and are covered in the lesson on tagged unions. ## Smart mode for plain types For scalars and other non-model types, smart mode scores each successful member into one of three exactness groups, highest first: an **exact type match**, a match that **would pass in strict mode**, and a match that **passes only in lax mode**. The steps are: 1. Try members from left to right. If one succeeds with an exact type match, return it immediately and try no more. 2. Otherwise, if any member succeeded as a strict match, return the leftmost of those. 3. Otherwise, if any member succeeded in lax mode, return the leftmost of those. 4. If every member failed, raise an error containing every member's errors. So with `ref: int | str` and input `'1042'`, the `str` member is an exact match and the value stays a string. With input `1042`, the `int` member is exact and wins. ## Smart mode for models For `BaseModel`, dataclass and `TypedDict` members, smart mode first counts the **number of valid fields set** by the input, including fields set on nested models, and the member with the highest count wins; exactness only breaks a tie. This metric was added in Pydantic 2.8.0; earlier 2.x releases used exactness alone. Picture a payment feed with an untagged `Charge | Refund` field where both models share `amount` and `Charge` has an optional `card_last4`. An input carrying `amount` and `original_charge_id` validates against both, because extra keys are ignored by default, but `Refund` sets two fields and `Charge` one, so `Refund` wins. Before 2.8 only exactness counted, so a tie like this could go to the leftmost member instead. The Pydantic documentation reserves the right to tweak the smart algorithm in later minor releases, which is why behaviour that matters should not lean on it. ## Left to right mode With `union_mode='left_to_right'`, each member is tried in declaration order and the **first success** is returned; if all fail, the error lists every member's errors. It must be set as a `Field` parameter on the union field, for example `ref: int | str = Field(union_mode='left_to_right')`. Order now carries meaning: `int | str` turns `'1042'` into the integer `1042`, because `int` comes first and converts the numeric string in lax mode, while `str | int` keeps it a string. This is how Pydantic 1 validated unions by default. Version 2 made smart mode the default and kept left to right as the documented way to get the old behaviour back. ## Comparing the modes | Question | Smart (default) | Left to right | |---|---|---| | Which member wins? | the best-scoring match | the first member that validates | | Does member order matter? | only as a tiebreaker | always | | Stable across minor releases? | not promised | yes | | Set by | nothing (default) | `Field(union_mode='left_to_right')` | | Errors on total failure | every member's errors | every member's errors | ## Choosing - Keep **smart** for simple scalar unions such as `int | str`, where preserving the input's own type is what you want. - Use **left to right** when you need a guaranteed order, for instance a migration where a legacy encoding must be tried first, and document why the order is what it is. - Use a **discriminated union** for unions of models. Pydantic's own documentation recommends it as more performant and more predictable than either untagged mode, and its errors name only the selected member. - Treat a surprising union result as a modelling smell: if two members can both accept the same input, the input format is ambiguous, and no mode makes it unambiguous.

  • In Pydantic 2, what does a union's error look like when no member validates?
    In both untagged modes the `ValidationError` contains errors from every member, each with the member's name in its `loc`, such as `id.str` and `id.int`. For a recursive model union this multiplies quickly, which is one reason the documentation recommends a discriminated union: it reports errors only for the selected member.
  • Why is relying on smart mode's exact tie-breaking behaviour risky in Pydantic 2?
    The documentation reserves the right to change the smart matching algorithm between minor releases; 2.8 already added the valid-fields-set metric, which changed outcomes for model unions. If correctness depends on which member wins, pin it with `union_mode='left_to_right'` or a discriminator instead.

  • Pydantic 2 always takes the first union member that validates.
  • In a smart union, int | str turns '1042' into the int 1042.
  • Smart mode's matching algorithm is guaranteed never to change between releases.
  • union_mode='left_to_right' is set once in ConfigDict for the whole model.
  • Member order has no effect in left to right mode.

Assumes Pydantic 2; version 1 accepted the first union member that validated, version 2 defaults to smart mode.