After a Pydantic 1 codebase moves to Pydantic 2 and every renamed API is fixed, which validation behaviours still change with no code change, and how do you catch them?
answer
- the renames are the easy part
- Optional no longer means a default
- numbers stop becoming strings
- fractions stop being truncated
- compare both versions on real payloads
basics
~20 sOptional fields without a default become required, numbers no longer coerce to str, floats with a fraction no longer truncate to int, int | str keeps '1' a string, and pairs stop becoming dicts. Replaying real payloads through both versions catches them.
solid answer
~50 sPydantic 2 tightened conversion, so identical models accept and produce different data. `Optional[str]` with no default is now required (a `missing` error) rather than defaulting to `None`. An `int` sent to a `str` field fails with `string_type` unless `coerce_numbers_to_str=True`. `2.5` into an `int` fails with `int_from_float`, where version 1 truncated it to 2. Smart unions keep `'7'` a string in an `int | str` field, where version 1 made it 7. A list of pairs no longer becomes a `dict`. On output, a subclass instance in a parent-typed field dumps only the parent's fields, and models no longer equal dicts. Most of these raise, but only on the inputs that trigger them, so tidy fixtures pass; the union, dump and equality changes raise nothing. Catch them by replaying recorded payloads through the old model, kept under `pydantic.v1`, and the new one, and diffing.
code
python · 20 linesfrom typing import Optional
from pydantic import BaseModel, ValidationError
class PriceUpdate(BaseModel):
note: Optional[str]
sku: str
quantity: int
ref: int | str
print(PriceUpdate(note=None, sku='A-1', quantity=10.0, ref='7'))
#> note=None sku='A-1' quantity=10 ref='7'
try:
PriceUpdate(sku=1001, quantity=2.5, ref=7)
except ValidationError as exc:
print([(error['loc'][0], error['type']) for error in exc.errors()])
#> [('note', 'missing'), ('sku', 'string_type'), ('quantity', 'int_from_float')]go deeper
Recall the headline changes: Optional without a default is required, numbers do not become strings, and fractional floats do not become ints.
Explain the error types you would see (missing, string_type, int_from_float, dict_type) and which config options restore version 1 behaviour.
Show why fixtures pass while production fails, and describe the differential test that runs pydantic.v1 and Pydantic 2 models on recorded payloads.
Decide per inbound contract whether to adopt the stricter rules and tell clients, or pin the old behaviour explicitly and schedule its removal.
## Why renames are not the whole migration A renaming tool can turn `.dict()` into `.model_dump()` because the change is visible in the source. The changes below are invisible: the model declaration is byte-for-byte the same, and Pydantic 2 simply does something different with the same input. The migration guide groups them under conversion, standard types and serialization. ## Input changes | Declaration and input | Version 1 | Pydantic 2 | How it surfaces | |---|---|---|---| | `note: Optional[str]`, field omitted | `None` | `missing` error | only on payloads that omit it | | `note: Any`, field omitted | `None` | `missing` error | only on payloads that omit it | | `sku: str`, given `1001` | `'1001'` | `string_type` error | only when a client sends a number | | `quantity: int`, given `2.5` | `2`, fraction lost | `int_from_float` error | `10.0` still becomes `10` | | `ref: int \| str`, given `'7'` | `7` | `'7'` | silently: the value's type changes | | `d: dict[str, int]`, given `[('a', 1)]` | a dict | `dict_type` error | only for pair-list inputs | | `Field(pattern=...)` with a lookahead | Python `re` | `SchemaError` at class definition | at import | The union row is the quiet one. Pydantic 2's default **smart** union mode keeps an input that already matches one member exactly, so a string stays a string; the left-to-right behaviour of version 1 is available per field with `Field(union_mode='left_to_right')`. The pattern row comes from Pydantic 2 using a Rust regex engine that runs in linear time and drops lookarounds and backreferences; `ConfigDict(regex_engine='python-re')` restores Python's engine where a pattern needs them. ## Output and comparison changes - **Subclass fields drop out of dumps.** If a field is typed `Address` and holds a `VerifiedAddress` subclass instance, version 1 dumped all subclass fields; Pydantic 2 dumps only the fields of the annotated type. The guide says this helps prevent some accidental security bugs. - **Models stop equalling dicts.** `ProductOut(...) == {'sku': ...}` is now `False`; equality needs the same model type, field values, private values and, with `extra='allow'`, extras. - **URL types are not strings.** `AnyUrl` no longer subclasses `str`, so code passing it to string APIs needs `str(url)`, and a URL with no path gains a trailing `/`. - **Container types are not preserved.** A `Counter` given to a `Mapping[str, int]` field comes back as a plain `dict`. ## Why ordinary tests miss them Every error row in the input table is loud, but only for the input that triggers it. A test fixture usually sends every field with its canonical type, so it passes on both versions. Production traffic includes the partner that sends quantities as `2.5` and SKUs as numbers. The quiet changes (union types, dropped subclass fields, equality) raise nothing at all. ## Reading the diff Each kind of difference points to a different decision: - **`missing` on the new side**: the field was optional in practice. Add an explicit default, or confirm clients always send it. - **`string_type` on the new side**: a client sends numbers where the model says `str`. Tell the client, or enable `coerce_numbers_to_str` on that model. - **`int_from_float` on the new side**: version 1 was silently discarding data. Usually fix the producer rather than restore truncation. - **Same success, different value type**: a union now keeps the input's type. Check the consumers, or set `union_mode='left_to_right'`. - **Fewer keys in a dump**: a subclass's extra fields no longer leave. Check whether they ever should have, since this change exists to stop accidental exposure. ## Catching them 1. **Collect real inputs.** Sample recorded request bodies, queue messages or fixture files that came from production, scrubbed as needed. 2. **Keep the old model alive in the test suite.** Pydantic 2 ships the version 1 library as `pydantic.v1`, so the old definition can sit beside the new one in a test module. 3. **Diff.** Validate each payload with both, then compare the version 1 `dict()` with the Pydantic 2 `model_dump()`, recording errors on either side. 4. **Decide per difference.** Either accept the stricter result (and tell clients), or restore the old behaviour explicitly: a default of `None`, `coerce_numbers_to_str=True`, `union_mode='left_to_right'`, or a before-mode validator. 5. **Keep the diff test** until the old definition is deleted, so later edits cannot reintroduce a gap.
- A client sends prices as numbers into a str field. How do you keep version 1 behaviour for that model only?Set `model_config = ConfigDict(coerce_numbers_to_str=True)` on that model; in lax mode it accepts `int`, `float` and `Decimal` into `str` fields again. Scope it to the inbound models that need it rather than a shared base, and record why, because it reverses a default Pydantic 2 chose on purpose.
- Which of these changes raise nothing at all, and why do they matter most?Smart unions changing a value's type, subclass fields dropping out of dumps, and models no longer equalling dicts. None raises, so neither error monitoring nor an assert-it-raises test sees them. They surface downstream: a consumer receives `'7'` where it expected 7, or a field disappears from an event. Only a value-level comparison of old and new output finds them.
- Once bump-pydantic has run and tests pass, behaviour is unchanged
- Optional[str] still means the field defaults to None
- Pydantic 2 still truncates 2.5 to 2 for an int field in lax mode
- Pydantic 2 strict mode reproduces version 1's coercion rules
- Every Pydantic 1 to 2 behaviour change shows up as a ValidationError
Assumes Pydantic 2 (checked on 2.14.0) against version 1.10: the conversion, union and Optional changes all arrived in 2.0 and differ from every version 1 release.