Typing & Pydantic v2: Annotated, Models, Validators, Serialization, Settings
"Pydantic guarantees the types and constraints of the output, not the input data." — Pydantic documentation, "Models", docs.pydantic.dev/latest/concepts/models
Summary: Python's type hints are metadata that the interpreter stores and ignores; static checkers (mypy, pyright) read them before the code runs, and Pydantic reads them at runtime to build a validator in Rust (pydantic-core) that turns untrusted input (a dict, a JSON string, an ORM row, environment variables) into typed objects or one ValidationError listing every problem. The same declaration also drives serialisation (model_dump, model_dump_json), aliases between the wire format and Python names, JSON Schema for OpenAPI, and typed settings (pydantic-settings). FastAPI is built on exactly this machinery. Focus: gradual typing, mypy and pyright, Optional/Union/X | None and from __future__ import annotations (and its trap on 3.9 and in FastAPI), Literal, TypedDict, Protocol and structural subtyping, Generic/TypeVar/ParamSpec, NewType, Final, overload, Self, TypeAlias and the 3.12 type statement, Annotated metadata; dataclass vs NamedTuple vs attrs vs Pydantic; Pydantic v2 BaseModel, lax mode vs strict mode and the conversion table, model_validate/model_validate_json, model_dump/model_dump_json with exclude_unset/exclude_none/by_alias, alias/validation_alias/serialization_alias/alias_generator, Field constraints, computed_field, field_validator/model_validator modes, AfterValidator/BeforeValidator/WrapValidator/PlainValidator, field_serializer/model_serializer, discriminated unions, generic models, RootModel, TypeAdapter, validate_call, model_config (extra, frozen, populate_by_name, from_attributes), JSON Schema, custom types and GetPydanticSchema, ValidationError.errors(), performance and defer_build, the v1 to v2 migration, BaseSettings, and DTOs vs domain objects. Learning goal: Read and write the type hints a modern Python backend uses, know which ones are checked statically and which ones Pydantic enforces at runtime, design input and output models that validate and serialise exactly what the API promises, load configuration that fails fast at startup, and recognise the v1-era and 3.9-era mistakes in existing code.
This page owns the language-level typing and Pydantic itself. It does not re-teach its neighbours: how FastAPI turns models into query, body, header and cookie parameters and into 422 responses is in Request Validation; wiring BaseSettings into an app with lifespan and dependencies is in APIRouter & Project Structure; the first contact with FastAPI, Starlette and Uvicorn is FastAPI Fundamentals; pyproject.toml, uv, Ruff and lock files are in Python Project Tooling; async def and the event loop are in Async Python; mapping models to tables with SQLAlchemy 2, SQLModel and Alembic is in SQLAlchemy 2 & SQLModel; pytest fixtures and httpx test clients are in Testing FastAPI. The Go equivalents are Structs, Methods & Struct Tags, Interfaces & Type Switches and JSON, XML & Struct Tags; wire formats in general are in Serialization Formats, and the design principles behind "depend on a Protocol, not a class" are in SOLID.
Facts below were checked against the Python documentation (typing, dataclasses, the annotations HOWTO, What's New in 3.9 to 3.14), PEPs 3107, 484, 526, 544, 563, 585, 589, 593, 604, 612, 613, 649, 655, 673, 695 and 749, the Pydantic documentation (concepts, API reference, error reference, migration guide, release history up to 2.14.4 of 2026-11-19), the pydantic-settings documentation, the mypy and pyright documentation, the attrs documentation, the FastAPI release notes, the Laravel 13 validation and Eloquent casts pages and the go-playground/validator README. The page is written for Python 3.12+ and current Pydantic. The snippets, however, were run on the only interpreter on the build machine, CPython 3.9.6, so the snippet project pins the newest releases that still install there: Pydantic 2.13.5 (2.14.0 dropped Python 3.9), pydantic-core 2.46.5, pydantic-settings 2.11.0 (2.12.0 requires 3.10), typing-extensions 4.16.0, eval-type-backport 0.4.0 so Pydantic can evaluate str | None on 3.9, pytest 8.4.2, and, as optional extras, mypy 1.19.1 (mypy 2.x needs 3.10), attrs 26.1.0, FastAPI 0.128.8 and httpx 0.28.1. The full resolved set is the snippet's requirements.lock. Every error text, error type, coercion result and timing quoted as "real" below is what that run printed; behaviour documented only for later releases is marked with the release.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why types, and why runtime validation on top | Why it exists |
| PEP 3107 (2006) to Pydantic 2.14 (2026) | Where it comes from |
| A before/after order payload | Python |
| Type hints, gradual typing, mypy, pyright | Type hints and static checkers |
Optional, Union, X | None, from __future__ import annotations | Optional, Union and the future import |
Literal, Final, NewType | Literal, Final, NewType |
TypedDict, NotRequired | TypedDict |
Protocol, duck typing for the checker | Protocol and structural subtyping |
Generic, TypeVar, ParamSpec, Self, overload | Generics, ParamSpec, Self, overload |
TypeAlias, type X = ... | TypeAlias and the type statement |
Annotated[int, Field(gt=0)] | Annotated and metadata |
| dataclass vs NamedTuple vs attrs vs Pydantic | Five ways to declare a record |
BaseModel, pydantic-core, Rust | BaseModel and pydantic-core |
"3" becomes 3? lax mode vs strict mode | Lax mode, strict mode, the conversion table |
model_validate, model_validate_json, model_construct | Validating input |
model_dump, exclude_unset, by_alias, serializers | Serialization |
| camelCase on the wire, snake_case in Python | Aliases |
Field(gt=0, max_length=20, pattern=...) | Field and constraints |
field_validator, model_validator, modes | Validators |
{"kind": "card"} picks the model | Discriminated unions |
Page[T], RootModel[list[str]] | Generic models and RootModel |
Validate a list[...] or a function's arguments | TypeAdapter and validate_call |
extra, frozen, from_attributes | model_config and ConfigDict |
| OpenAPI from models | JSON Schema |
| A type Pydantic does not know | Custom types and GetPydanticSchema |
errors(), loc, type, msg, input | ValidationError |
| How fast, and how to keep it fast | Performance and defer_build |
parse_obj, .dict(), orm_mode | v1 to v2 migration |
Environment variables, .env, secrets | pydantic-settings |
| Where Pydantic belongs in the architecture | DTO vs domain object |
What happens inside one model_validate call | Mechanics |
| The common bugs and their fixes | Solving the classic problems |
| Pydantic or a dataclass or a TypedDict? | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
Form Requests and $casts | For PHP/Laravel developers |
| Struct tags and go-playground/validator | The Go angle |
Everything in one minute
The typing toolbox. Every row is unpacked in the concept catalogue. "Runtime" means what Python itself does with the hint: almost always nothing.
| Construct | Meaning | Since | Checked by mypy/pyright | Enforced by Pydantic at runtime |
|---|---|---|---|---|
x: int | Annotation | 3.0 (functions), 3.6 (variables) | Yes | Yes, with lax-mode conversion |
Optional[int] / int | None | int or None | 3.5 / 3.10 | Yes | Yes |
Union[int, str] / int | str | Either type | 3.5 / 3.10 | Yes | Yes (smart mode) |
Literal["EUR", "USD"] | Exactly these values | 3.8 | Yes | Yes |
Final | Never reassigned | 3.8 | Yes | No |
NewType("UserId", int) | Distinct static type, same runtime value | 3.5.2 | Yes | Validated as int |
TypedDict | Shape of a dict | 3.8 | Yes | Yes (typing_extensions version on < 3.12) |
Protocol | "Has these methods" | 3.8 | Yes | No (only isinstance with @runtime_checkable, names only) |
Generic[T], TypeVar | Type parameters | 3.5 | Yes | Yes, on BaseModel generics |
ParamSpec | A callable's parameter list | 3.10 | Yes | No |
Self | "The class this method is called on" | 3.11 | Yes | No |
@overload | Several signatures, one implementation | 3.5 | Yes | No |
TypeAlias / type X = ... | Named alias | 3.10 / 3.12 | Yes | Yes (the aliased type) |
Annotated[T, meta] | T plus metadata | 3.9 | T only | Yes: Field, validators, Strict |
Pydantic v2 in one table.
| Task | API | Plain words |
|---|---|---|
| Declare a model | class OrderIn(BaseModel): ... | Fields from annotations |
| Python object to model | OrderIn.model_validate(data) | Validate a dict or object |
| JSON text to model | OrderIn.model_validate_json(text) | Parse and validate in Rust in one pass |
| Trusted data, no checks | OrderIn.model_construct(**data) | Skip validation |
| Model to dict | m.model_dump(mode="python" | "json") | mode="json" gives JSON-safe values |
| Model to JSON | m.model_dump_json(by_alias=True) | Returns str, serialised in Rust (TypeAdapter.dump_json returns bytes) |
| Only what the client sent | model_dump(exclude_unset=True) | Partial updates (PATCH) |
Drop None values | model_dump(exclude_none=True) | Compact output |
| Copy with changes | m.model_copy(update={...}) | Not validated |
| JSON Schema | OrderIn.model_json_schema() | What FastAPI puts in OpenAPI |
| Non-model types | TypeAdapter(list[OrderLine]) | Same engine for any type |
| Validate function arguments | @validate_call | Pydantic at a function boundary |
| Configuration | model_config = ConfigDict(...) | Per-model behaviour |
| Settings | class Settings(BaseSettings) | Environment variables to typed config |
Validators: which mode sees what. Real order from the snippet run (tests/test_models.py).
| Validator | Sees | Runs | Typical use |
|---|---|---|---|
@model_validator(mode="before") | Raw input (dict, object, anything) | First, once per model | Rename legacy keys, unwrap envelopes |
BeforeValidator / @field_validator(mode="before") | Raw field value | Before the core type check | "" → None, strip, split CSV |
WrapValidator / mode="wrap" | Raw value + handler | Around the core check | Fallbacks, truncation, timing |
| core validator (Rust) | Raw value | Type + coercion + Field constraints | Always, unless replaced |
PlainValidator / mode="plain" | Raw value | Instead of the core check | A completely custom rule |
AfterValidator / @field_validator (default "after") | Typed value | After the core check | Business rules on a valid value |
@model_validator(mode="after") | The built instance | Last | Cross-field rules |
Config keys you will set.
| Key | Default | Effect |
|---|---|---|
extra | "ignore" (BaseModel), "forbid" (BaseSettings) | "ignore", "forbid" (error extra_forbidden) or "allow" (kept in model_extra) |
strict | False | Strict mode for every field |
frozen | False | Assignment raises frozen_instance; __hash__ is generated, so instances are hashable only if every field value is; shallow (a dict field can still be mutated) |
from_attributes | False | Read objects (ORM rows, dataclasses) by attribute |
alias_generator | None | e.g. to_camel: customer_email ↔ customerEmail |
populate_by_name / validate_by_name (2.11+) | False | Accept the Python name as well as the alias |
serialize_by_alias (2.11+) | False | Dump by alias without passing by_alias=True |
validate_assignment | False | Re-validate on m.x = ... |
str_strip_whitespace | False | Strip strings before validation |
defer_build | False | Build the validator on first use |
regex_engine | "rust-regex" | "python-re" for look-arounds |
Why it exists
Python is dynamically typed: a function declared def total(qty: int) happily runs with qty="ab" and returns "abab" (the snippet's annotations_are_not_enforced does exactly that). In a script that is convenience; in a backend that receives JSON from browsers, mobile apps, partners and message queues it is a bug factory, because every value arrives as a string, a number, a list or a dict that may or may not have the shape the code assumes. Two separate tools close the gap. Static type checkers (mypy, pyright) read annotations before the code runs and catch the programmer's mistakes: passing a UserId where an OrderId is expected, indexing a value that may be None, calling a method that does not exist. Runtime validation (Pydantic) catches the outside world's mistakes: a quantity of "two", a missing email, an unknown payment kind, an extra isAdmin key. Pydantic's insight is that the same annotations can drive both, so the declaration you write once is the documentation, the static contract, the parser, the validator, the serialiser and the JSON Schema.
| Hand-written checks on dicts (the Before code) | Annotated models (Pydantic v2) |
|---|---|
| Shape lives in the code that reads it | Shape is a class with typed fields |
| First error stops the check | All errors in one ValidationError |
int("2.7") crashes, int(2.7) truncates silently | int_from_float error for 2.7, "2" → 2 |
Unknown keys ride along (isAdmin) | extra="forbid" rejects them |
Output mapping written separately, json.dumps fails on Decimal | model_dump_json() with the same field rules |
| Nothing for the type checker | mypy/pyright see real classes and types |
| Docs written by hand | model_json_schema() feeds OpenAPI |
An everyday picture. An airport. The type hints are the signs and floor markings: "passengers only", "gate B12", "max 7 kg". Nobody is stopped by a sign; it tells people (and the staff who plan the building, the static checker) what is supposed to happen, and a planner can spot that two signs contradict each other before the airport opens. Pydantic is the check-in desk and security: every bag is weighed (constraints), a passport that says "12/05/1990" is read into a date (lax conversion), a bag without a label is refused, and the passenger gets one sheet listing everything wrong (one ValidationError) instead of being sent back once per problem. Strict mode is the desk that refuses a handwritten boarding pass even though the information on it is correct. Serialization is printing the boarding pass in the format the gate scanner expects (aliases, JSON). The domain object is the passenger once airside: nobody re-checks the passport at every shop. Settings are the airport's own operating licence, checked once at opening; if it is missing, the airport does not open.
Three common misunderstandings, up front
- "Type hints make Python check types." They do not: "The Python runtime does not enforce function and variable type annotations." Checks happen in mypy/pyright (before running) or in a library such as Pydantic that reads the hints (at runtime). A typed function called with the wrong type still runs.
- "Pydantic validates that the input is correct." It builds an output that is correct. In the default lax mode
"3"becomes3,"yes"becomesTrueand"2026-11-29"becomes adatetime; the input was not "valid" in a strict sense, but the model is. If conversion is not what you want, use strict mode. - "One Pydantic model per resource is enough." Input and output have different rules (an
idthe client must not send, apasswordthe API must not return, aPATCHwhere every field is optional). Separate input DTOs, output DTOs and the domain object; FastAPI'sresponse_modelandexclude_unsetexist because of this.
Where it comes from
PEP 3107 (created 2006-12-02) gave Python 3.0 function annotations with no meaning attached. PEP 484 (created 2014-09-29, Python 3.5) gave them a meaning and added the typing module, while promising "It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention." PEP 526 (3.6) added variable annotations, PEP 586 (3.8) Literal, PEP 591 (3.8) Final, PEP 544 (3.8) Protocol ("Structural subtyping (static duck typing)"), PEP 589 (3.8) TypedDict, PEP 563 (3.7) the from __future__ import annotations switch that stores annotations as strings, PEP 585 (3.9) list[int] instead of List[int], PEP 593 (3.9) Annotated, PEP 604 (3.10) X | Y, PEP 612 (3.10) ParamSpec, PEP 613 (3.10) TypeAlias, PEP 655 (3.11) NotRequired, PEP 673 (3.11) Self, and PEP 695 (3.12) the type statement and class Box[T] syntax. Python 3.13 added type-parameter defaults (PEP 696), ReadOnly (PEP 705) and TypeIs (PEP 742). Python 3.14 shipped PEP 649/749, "Deferred evaluation of annotations", and its What's New says of from __future__ import annotations: "this statement is now deprecated and it is expected to be removed in a future version of Python. This removal will not happen until after Python 3.13 reaches its end of life in 2029".
Pydantic 1.0 was released on 2019-10-23 (PyPI upload date; the HISTORY file has the same date). Pydantic 2.0 (2023-06-30) rewrote the core in Rust as pydantic-core; FastAPI 0.100.0 (2023-07-07) added "Support for Pydantic v2" ("Pydantic version 2 has the core re-written in Rust"), and FastAPI 0.126.0 (2025-12-20) dropped Pydantic v1. The pydantic-core repository README now says it is "the (archived) original home of pydantic-core" and that the code "now resides inside the main pydantic repository". Pydantic 2.11 (2025-03-27) added validate_by_name, validate_by_alias and serialize_by_alias ("populate_by_name usage is not recommended in v2.11+ and will be deprecated in v3"), 2.13 (2026-04-13) is the last minor line for Python 3.9, and 2.14.0 (2026-10-08) "drops support for Python 3.9 and adds support for Python 3.15". pydantic-settings split out of Pydantic with 2.0.0 (2023-06-30); its latest release, 2.16.3 (2026-11-13), requires Python 3.11.
1 2006-12 PEP 3107: function annotations (Python 3.0), no semantics
2 2014-09 PEP 484: type hints + typing module (3.5); mypy is the reference checker
3 2016-08 PEP 526: variable annotations (3.6)
4 2017 PEP 563 (3.7): from __future__ import annotations; PEP 544 Protocol (3.8)
5 2019-10 Pydantic 1.0
6 2019-2020 PEP 585 list[int] + PEP 593 Annotated (3.9); PEP 604 X | Y, 612 ParamSpec, 613 TypeAlias (3.10)
7 2021-11 PEP 673 Self, PEP 655 NotRequired (3.11, October 2022)
8 2022-06 PEP 695 type statement and class Box[T] (3.12, October 2023)
9 2023-06 Pydantic 2.0: pydantic-core in Rust; pydantic-settings 2.0.0 split out
10 2023-07 FastAPI 0.100.0 supports Pydantic v2
11 2025-03 Pydantic 2.11: validate_by_name / validate_by_alias / serialize_by_alias
12 2025-10 Python 3.14: deferred evaluation of annotations; future import deprecated
13 2025-12 FastAPI 0.126.0 drops Pydantic v1
14 2026-10 Pydantic 2.14.0 drops Python 3.9; 2.14.4 on 2026-11-19Python
Before
An order endpoint's payload handled as a plain dict. It works for the happy path: every rule is an if, the first problem stops the check, numbers are converted by hand (and 2.7 silently becomes 2), the payment shape is checked in one place by string comparison, unknown keys such as isAdmin ride along, and the output side is a second hand-written mapping that cannot even serialise its own Decimal and datetime values. dict[str, Any] keeps mypy quiet and checks nothing.
"""Before: an order payload handled as an untyped dict.
Bad design, not broken code: it runs, but every rule is hand-written, the first
problem stops the check, types are guessed, unknown keys are kept, and the
output side is a second hand-written mapping that drifts from the input side.
"""
from __future__ import annotations
import json
from datetime import datetime
from decimal import Decimal
from typing import Any
def parse_order(raw: dict[str, Any]) -> dict[str, Any]:
# dict[str, Any] satisfies `mypy --strict` and still checks nothing: Any switches the checker off.
# No declared shape: callers learn the keys by reading this function.
if "customerEmail" not in raw:
raise ValueError("customerEmail is required") # stops at the first problem
if "@" not in raw["customerEmail"]:
raise ValueError("bad email")
lines = raw.get("lines") or []
for line in lines:
# "2" and 2 and 2.7 are all accepted; int("2.7") would crash, int(2.7) truncates silently.
line["qty"] = int(line["qty"])
if line["qty"] <= 0:
raise ValueError("qty must be positive")
line["unit_price"] = Decimal(str(line["unit_price"]))
# Payment shape depends on a string the code checks by hand, in one place only.
payment = raw.get("payment", {})
if payment.get("kind") == "card" and len(str(payment.get("last4", ""))) != 4:
raise ValueError("last4")
raw["placed_at"] = datetime.fromisoformat(raw["placedAt"])
return raw # extra keys such as "isAdmin" ride along untouched
def order_to_json(order: dict[str, Any]) -> str:
# A second, hand-written mapping for the output; it already forgot that
# Decimal and datetime are not JSON-serialisable by the standard library.
return json.dumps({"email": order["customerEmail"], "lines": order["lines"], "placedAt": order["placed_at"]})The tests pin each problem down:
"""Pins down what the untyped dict version gets wrong."""
from __future__ import annotations
from typing import Any
import pytest
from app.before import order_to_json, parse_order
def test_stops_at_first_error_only() -> None:
raw: dict[str, Any] = {"customerEmail": "nope", "lines": [{"qty": "0", "unit_price": "x"}]}
with pytest.raises(ValueError, match="bad email"): # the qty problem is never reported
parse_order(raw)
def test_float_quantity_is_truncated_silently(order_payload: dict[str, Any]) -> None:
order_payload["lines"] = [{"qty": 2.7, "unit_price": "1"}]
assert parse_order(order_payload)["lines"][0]["qty"] == 2 # Pydantic: int_from_float error
def test_unknown_keys_survive(order_payload: dict[str, Any]) -> None:
order_payload["isAdmin"] = True
order_payload["lines"] = [{"qty": 1, "unit_price": "1"}]
assert parse_order(order_payload)["isAdmin"] is True # mass-assignment risk
def test_output_mapping_cannot_serialise_its_own_types(order_payload: dict[str, Any]) -> None:
order_payload["lines"] = [{"qty": 1, "unit_price": "9.99"}]
with pytest.raises(TypeError, match="not JSON serializable"):
order_to_json(parse_order(order_payload))After
The same payload as Pydantic v2 models. CamelModel carries the shared alias configuration (a nested model does not inherit its parent's model_config, which the first run of this snippet proved with a missing error on lines.0.unit_price); reusable constrained types are Annotated aliases; Money is a frozen value object; payments are a discriminated union; OrderIn is the input DTO with extra="forbid" and validators in every mode; OrderOut is the output DTO that reads domain objects with from_attributes; Page[T] is a generic model and Tags a RootModel.
"""After: the order API's transport models (DTOs) in Pydantic v2.
Input DTO (OrderIn) -> domain object (app.domain.Order) -> output DTO (OrderOut).
Module-level aliases are evaluated at import time, so they use Optional/Union
(3.9); annotations inside classes may use `X | None` thanks to the __future__
import plus eval-type-backport.
"""
from __future__ import annotations
import re
from datetime import datetime, timezone
from decimal import Decimal
from typing import Annotated, Any, Generic, Literal, TypeVar, Union
from pydantic import (
AfterValidator,
AliasChoices,
BaseModel,
BeforeValidator,
ConfigDict,
Discriminator,
Field,
PlainValidator,
RootModel,
SerializerFunctionWrapHandler,
Tag,
ValidationError,
ValidatorFunctionWrapHandler,
WrapValidator,
computed_field,
field_serializer,
field_validator,
model_serializer,
model_validator,
)
from pydantic.alias_generators import to_camel
MAX_LINES = 50
SKU_RE = re.compile(r"^[A-Z]{3}-\d{4}$")
# --- Reusable constrained types: Annotated[type, *metadata] -------------------------------
def _normalise_sku(value: Any) -> Any: # BeforeValidator: runs on the raw input
return value.strip().upper() if isinstance(value, str) else value
def _check_sku(value: str) -> str: # AfterValidator: runs on an already valid str
if not SKU_RE.match(value):
raise ValueError("SKU must look like ABC-1234")
return value
Sku = Annotated[str, AfterValidator(_check_sku), BeforeValidator(_normalise_sku)]
Qty = Annotated[int, Field(gt=0, le=1000)]
def _truncate(value: Any, handler: ValidatorFunctionWrapHandler) -> str:
# WrapValidator: decide around the inner validation (here: shorten instead of failing).
try:
result: str = handler(value)
except ValidationError as err:
if err.errors()[0]["type"] != "string_too_long":
raise
result = handler(value[:200])
return result
Note = Annotated[str, Field(max_length=200), WrapValidator(_truncate)]
def _parse_flag(value: Any) -> bool:
# PlainValidator: replaces Pydantic's bool rules entirely ("1", "on", "t" are NOT accepted).
if value in (True, "yes"):
return True
if value in (False, "no"):
return False
raise ValueError("use yes or no")
Flag = Annotated[bool, PlainValidator(_parse_flag)]
class CamelModel(BaseModel):
"""Shared config. model_config is per class: a nested model does NOT inherit the
parent's alias_generator, so every wire model derives from this base."""
model_config = ConfigDict(
alias_generator=to_camel, # customer_email <-> customerEmail
populate_by_name=True, # also accept customer_email (2.11+: validate_by_name=True)
)
# --- Value object: immutable, compared by value -----------------------------------------
class Money(BaseModel):
model_config = ConfigDict(frozen=True)
amount: Decimal = Field(ge=0, max_digits=12, decimal_places=2)
currency: Literal["EUR", "USD", "IRR"] = "EUR"
@field_serializer("amount")
def _amount_as_string(self, amount: Decimal) -> str:
return f"{amount:.2f}" # never a float in JSON
class OrderLine(CamelModel):
sku: Sku
qty: Qty
unit_price: Money
@computed_field # type: ignore[prop-decorator]
@property
def line_total(self) -> Money:
return Money(amount=self.unit_price.amount * self.qty, currency=self.unit_price.currency)
# --- Discriminated (tagged) union: the "kind" field picks the model -----------------------
class Card(BaseModel):
kind: Literal["card"] = "card"
brand: Literal["visa", "mastercard"]
last4: str = Field(pattern=r"^\d{4}$")
class BankTransfer(BaseModel):
kind: Literal["bank"] = "bank"
iban: str = Field(min_length=15, max_length=34)
class Wallet(BaseModel):
kind: Literal["wallet"] = "wallet"
provider: str
Payment = Annotated[Union[Card, BankTransfer, Wallet], Field(discriminator="kind")]
def _payment_tag(value: Any) -> str | None:
# Callable discriminator for legacy payloads that have no "kind" key.
if isinstance(value, dict):
if "kind" in value:
return str(value["kind"])
return "card" if "last4" in value else "bank" if "iban" in value else None
return getattr(value, "kind", None)
LegacyPayment = Annotated[
Union[Annotated[Card, Tag("card")], Annotated[BankTransfer, Tag("bank")], Annotated[Wallet, Tag("wallet")]],
Discriminator(_payment_tag),
]
# --- Input DTO ---------------------------------------------------------------------------
class OrderIn(CamelModel):
"""What a client may send. camelCase on the wire, snake_case in Python."""
model_config = ConfigDict( # merged with CamelModel's config
extra="forbid", # unknown keys (isAdmin) are an error, not ignored
str_strip_whitespace=True,
)
customer_email: str = Field(max_length=254, pattern=r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$")
lines: list[OrderLine] = Field(min_length=1, max_length=MAX_LINES)
payment: Payment
coupon: str | None = None
placed_at: datetime = Field(validation_alias=AliasChoices("placedAt", "placed_at", "createdAt"))
note: Note = ""
gift: Flag = False
@model_validator(mode="before")
@classmethod
def _accept_legacy_items(cls, data: Any) -> Any:
# mode="before": the raw input (a dict here), before any field is validated.
if isinstance(data, dict) and "items" in data and "lines" not in data:
data = {**data, "lines": data["items"]}
del data["items"]
return data
@field_validator("customer_email")
@classmethod
def _lower_email(cls, value: str) -> str: # mode="after" (default): value is already a str
return value.lower()
@field_validator("coupon", mode="before")
@classmethod
def _blank_coupon_is_none(cls, value: Any) -> Any:
return None if value == "" else value
@model_validator(mode="after")
def _one_currency(self) -> OrderIn:
# mode="after": every field is valid; cross-field rules go here.
currencies = {line.unit_price.currency for line in self.lines}
if len(currencies) > 1:
raise ValueError(f"all lines must use one currency, got {sorted(currencies)}")
if self.placed_at.tzinfo is None:
raise ValueError("placedAt must include a timezone offset")
return self
# --- Output DTO --------------------------------------------------------------------------
class OrderOut(CamelModel):
"""What the API returns. from_attributes reads ORM rows (SQLAlchemy/SQLModel) or domain objects."""
model_config = ConfigDict(from_attributes=True)
id: int
status: Literal["pending", "paid", "shipped", "cancelled"]
customer_email: str
total: Money
placed_at: datetime
@field_serializer("placed_at")
def _utc_z(self, value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@computed_field # type: ignore[prop-decorator]
@property
def is_paid(self) -> bool:
return self.status in ("paid", "shipped")
# --- Generic model and a wrap model_serializer -------------------------------------------
T = TypeVar("T")
class Page(BaseModel, Generic[T]):
items: list[T]
total: int = Field(ge=0)
next_cursor: str | None = None
@model_serializer(mode="wrap")
def _add_count(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
data: dict[str, Any] = handler(self) # the default serialisation ...
data["count"] = len(self.items) # ... plus one derived key
return data
# --- RootModel: a model whose value is not a dict ----------------------------------------
class Tags(RootModel[list[str]]):
@field_validator("root")
@classmethod
def _dedupe(cls, value: list[str]) -> list[str]:
return sorted({tag.strip().lower() for tag in value if tag.strip()})
# --- Lax vs strict side by side ----------------------------------------------------------
class LaxLine(BaseModel):
qty: int
price: Decimal
placed_at: datetime
class StrictLine(BaseModel):
model_config = ConfigDict(strict=True)
qty: int
price: Decimal
placed_at: datetimeThe domain object is deliberately a plain dataclass: it has behaviour (pay(), total) and no wire format.
"""The domain object: behaviour and invariants, no wire format.
A plain dataclass on purpose: it does not know about aliases, JSON or HTTP.
Pydantic DTOs convert at the edge (OrderIn -> Order -> OrderOut).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal
from app.models import Money, OrderIn
class InvalidTransition(Exception):
pass
@dataclass
class Order:
id: int
customer_email: str
lines: list[tuple[str, int, Decimal]]
currency: str
placed_at: datetime
status: str = "pending"
events: list[str] = field(default_factory=list)
@classmethod
def from_dto(cls, order_id: int, dto: OrderIn) -> Order:
return cls(
id=order_id,
customer_email=dto.customer_email,
lines=[(line.sku, line.qty, line.unit_price.amount) for line in dto.lines],
currency=dto.lines[0].unit_price.currency,
placed_at=dto.placed_at,
)
@property
def total(self) -> Money:
amount = sum((qty * price for _, qty, price in self.lines), Decimal("0"))
return Money(amount=amount, currency=self.currency)
def pay(self) -> None:
if self.status != "pending":
raise InvalidTransition(f"cannot pay an order that is {self.status}")
self.status = "paid"
self.events.append("OrderPaid")The tests cover validation in every mode, the error list, aliases, extra="forbid", dumps with exclude_unset/exclude_none/exclude_defaults, computed fields and the JSON round trip:
from __future__ import annotations
from typing import Any
import pytest
@pytest.fixture()
def order_payload() -> dict[str, Any]:
"""A valid order as a client sends it: camelCase keys, strings for numbers."""
return {
"customerEmail": " Ana@Example.COM ",
"lines": [
{"sku": " abc-1234", "qty": "2", "unitPrice": {"amount": "12.50", "currency": "EUR"}},
{"sku": "XYZ-0001", "qty": 1, "unitPrice": {"amount": 3, "currency": "EUR"}},
],
"payment": {"kind": "card", "brand": "visa", "last4": "4242"},
"placedAt": "2026-11-29T10:00:00+03:30",
}"""OrderIn: aliases, constraints, validators in every mode, extra="forbid", exclude_* dumps."""
from __future__ import annotations
from decimal import Decimal
from typing import Any
import pytest
from pydantic import ValidationError
from app.models import Money, OrderIn, OrderLine
def test_valid_payload_is_converted(order_payload: dict[str, Any]) -> None:
order = OrderIn.model_validate(order_payload)
assert order.customer_email == "ana@example.com" # strip + field_validator(after) lower()
assert order.lines[0].sku == "ABC-1234" # BeforeValidator normalised, AfterValidator checked
assert order.lines[0].qty == 2 # "2" -> 2 (lax mode)
assert order.lines[1].unit_price.amount == Decimal("3")
assert order.placed_at.utcoffset().total_seconds() == 12600 # +03:30
assert order.lines[0].line_total == Money(amount=Decimal("25.00"), currency="EUR")
def test_all_errors_reported_at_once(order_payload: dict[str, Any]) -> None:
order_payload["customerEmail"] = "not-an-email"
order_payload["lines"][0]["qty"] = 0
order_payload["lines"][1]["sku"] = "bad"
with pytest.raises(ValidationError) as exc:
OrderIn.model_validate(order_payload)
got = [(e["loc"], e["type"]) for e in exc.value.errors()]
assert got == [
(("customerEmail",), "string_pattern_mismatch"),
(("lines", 0, "qty"), "greater_than"),
(("lines", 1, "sku"), "value_error"),
]
assert exc.value.error_count() == 3
assert exc.value.title == "OrderIn"
def test_error_dict_shape(order_payload: dict[str, Any]) -> None:
order_payload["lines"][0]["qty"] = "two"
with pytest.raises(ValidationError) as exc:
OrderIn.model_validate(order_payload)
(err,) = exc.value.errors(include_url=False)
assert err == {
"type": "int_parsing",
"loc": ("lines", 0, "qty"),
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "two",
}
def test_extra_forbid(order_payload: dict[str, Any]) -> None:
order_payload["isAdmin"] = True
with pytest.raises(ValidationError) as exc:
OrderIn.model_validate(order_payload)
assert exc.value.errors()[0]["type"] == "extra_forbidden"
assert exc.value.errors()[0]["loc"] == ("isAdmin",)
def test_nested_models_do_not_inherit_config() -> None:
# OrderLine is not extra="forbid": its unknown keys are ignored (the default).
line = OrderLine.model_validate({"sku": "ABC-1234", "qty": 1, "unitPrice": {"amount": 1}, "colour": "red"})
assert not hasattr(line, "colour")
def test_populate_by_name_accepts_python_names(order_payload: dict[str, Any]) -> None:
order_payload["customer_email"] = order_payload.pop("customerEmail")
assert OrderIn.model_validate(order_payload).customer_email == "ana@example.com"
assert OrderIn.model_config["validate_by_name"] is True # 2.11+: populate_by_name sets both
def test_validation_alias_choices(order_payload: dict[str, Any]) -> None:
order_payload["createdAt"] = order_payload.pop("placedAt")
assert OrderIn.model_validate(order_payload).placed_at.year == 2026
def test_model_validator_before_renames_legacy_key(order_payload: dict[str, Any]) -> None:
order_payload["items"] = order_payload.pop("lines")
assert len(OrderIn.model_validate(order_payload).lines) == 2
def test_model_validator_after_cross_field(order_payload: dict[str, Any]) -> None:
order_payload["lines"][1]["unitPrice"]["currency"] = "USD"
with pytest.raises(ValidationError, match=r"one currency, got \['EUR', 'USD'\]"):
OrderIn.model_validate(order_payload)
order_payload["lines"][1]["unitPrice"]["currency"] = "EUR"
order_payload["placedAt"] = "2026-11-29T10:00:00" # naive datetime
with pytest.raises(ValidationError, match="timezone offset"):
OrderIn.model_validate(order_payload)
def test_before_field_validator_and_wrap_and_plain(order_payload: dict[str, Any]) -> None:
order_payload.update(coupon="", note="x" * 250, gift="yes")
order = OrderIn.model_validate(order_payload)
assert order.coupon is None # mode="before": "" -> None
assert len(order.note) == 200 # WrapValidator truncated instead of failing
assert order.gift is True # PlainValidator: only yes/no
order_payload["gift"] = "true"
with pytest.raises(ValidationError, match="use yes or no"):
OrderIn.model_validate(order_payload)
def test_field_constraints() -> None:
with pytest.raises(ValidationError) as exc:
Money(amount=Decimal("1.999"))
assert exc.value.errors()[0]["type"] == "decimal_max_places"
with pytest.raises(ValidationError) as exc:
OrderLine.model_validate({"sku": "ABC-1234", "qty": 1001, "unitPrice": {"amount": 1}})
assert exc.value.errors()[0]["type"] == "less_than_equal"
def test_frozen_value_object() -> None:
m = Money(amount=Decimal("1.00"))
with pytest.raises(ValidationError) as exc:
m.amount = Decimal("2") # type: ignore[misc]
assert exc.value.errors()[0]["type"] == "frozen_instance"
assert hash(m) == hash(Money(amount=Decimal("1.00"))) # frozen models are hashable
def test_assignment_is_not_validated_by_default(order_payload: dict[str, Any]) -> None:
order = OrderIn.model_validate(order_payload)
order.customer_email = 42 # type: ignore[assignment] # no validate_assignment=True
assert order.customer_email == 42
def test_model_construct_skips_validation() -> None:
raw = Money.model_construct(amount="not a number") # trusted data only
assert raw.amount == "not a number"
def test_dump_options(order_payload: dict[str, Any]) -> None:
order = OrderIn.model_validate(order_payload)
by_alias = order.model_dump(by_alias=True, mode="json", include={"customer_email", "placed_at"})
assert by_alias == {"customerEmail": "ana@example.com", "placedAt": "2026-11-29T10:00:00+03:30"}
unset = order.model_dump(exclude_unset=True)
assert "coupon" not in unset and "note" not in unset # never sent by the client
assert order.model_dump(exclude_none=True).get("coupon", "absent") == "absent"
assert order.model_dump(exclude_defaults=True).get("gift", "absent") == "absent"
assert order.lines[0].model_dump()["unit_price"]["amount"] == "12.50" # field_serializer
def test_computed_field_is_serialised_not_validated(order_payload: dict[str, Any]) -> None:
order = OrderIn.model_validate(order_payload)
dumped = order.lines[0].model_dump(by_alias=True)
assert dumped["lineTotal"] == {"amount": "25.00", "currency": "EUR"}
line = dict(order_payload["lines"][0], lineTotal={"amount": "999"})
assert OrderLine.model_validate(line).line_total.amount == Decimal("25.00") # input ignored
def test_json_round_trip(order_payload: dict[str, Any]) -> None:
order = OrderIn.model_validate(order_payload)
text = order.model_dump_json(by_alias=True, exclude={"lines": {"__all__": {"line_total"}}})
assert OrderIn.model_validate_json(text) == orderThe project file pins the stack (see the version note at the top of the page) and runs mypy in strict mode with the Pydantic plugin:
[project]
name = "python-typing-pydantic"
version = "0.1.0"
description = "Snippets for the Typing & Pydantic v2 chapter: type hints, models, validators, serialization, TypeAdapter, settings"
# The page targets Python 3.12+ and current Pydantic. The pins below are the newest releases that
# still install on 3.9, the only interpreter on the build machine (pydantic 2.14.0 and
# pydantic-settings 2.12.0 dropped 3.9). On 3.12+ move to the latest releases.
requires-python = ">=3.9"
dependencies = [
"pydantic==2.13.5",
"pydantic-settings==2.11.0",
# Self, ParamSpec, TypeAlias, NotRequired, TypedDict for Pydantic on < 3.12.
"typing-extensions==4.16.0",
# Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
"eval-type-backport==0.4.0; python_version < '3.10'",
]
[project.optional-dependencies]
test = [
"pytest==8.4.2",
]
# Only for tests/test_fastapi_trap.py (the __future__ annotations trap inside FastAPI).
fastapi = [
"fastapi==0.128.8",
"httpx==0.28.1",
]
# Static checking and the dataclass/attrs comparison (tests skip when these are absent).
# FastAPI is included because mypy type-checks app/fastapi_trap.py.
dev = [
"mypy==1.19.1",
"attrs==26.1.0",
"fastapi==0.128.8",
"httpx==0.28.1",
]
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["app"]
[tool.mypy]
python_version = "3.9"
strict = true
plugins = ["pydantic.mypy"]
# app/static_errors.py is wrong on purpose; the test runs mypy on it and asserts the findings.
exclude = ["app/static_errors\\.py"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]The Python angle
Three language features carry this whole chapter. Annotations are data: Model.__annotations__ (or typing.get_type_hints) returns them, and Pydantic reads them once, at class creation, to build a core schema that pydantic-core compiles into a validator and a serialiser; that is why a model class costs something to create and almost nothing to use. Strings vs objects: with from __future__ import annotations (PEP 563) every annotation is stored as a string (Page.__annotations__["next_cursor"] == "str | None", asserted in test_typing_toolbox.py), and anything that needs the real type has to evaluate the string later, in the right namespace; on 3.9 evaluating "str | None" raises TypeError: unsupported operand type(s) for |: 'type' and 'NoneType', which eval-type-backport works around for Pydantic only. Annotated (PEP 593) lets one annotation carry both the type the checker sees and the metadata the runtime uses (Annotated[int, Field(gt=0)]). On Python 3.12+ you would write type Payment = Annotated[Card | BankTransfer | Wallet, Field(discriminator="kind")] and class Page[T](BaseModel) (PEP 695); the snippets use Union[...], TypeVar and Generic[T] because they must run on 3.9, and module-level aliases there cannot use | because they are evaluated immediately.
The concept catalogue
The first eight blocks are the language (the typing module and the checkers); the rest are Pydantic. The typing toolbox used below is one file that runs on 3.9 and passes mypy --strict:
"""The typing toolbox a backend uses daily, written to run on 3.9 and to pass `mypy --strict`.
`from __future__ import annotations` (PEP 563) keeps every annotation as a string, so
`int | None` in a signature is fine on 3.9. Anything evaluated at runtime (aliases,
isinstance, TypeAdapter(...)) still needs Optional/Union on 3.9.
"""
from __future__ import annotations
import functools
import time
from dataclasses import dataclass, field
from typing import (
Callable,
Dict,
Final,
Generic,
Iterable,
Literal,
NewType,
Optional,
Protocol,
TypeVar,
Union,
overload,
runtime_checkable,
)
from typing_extensions import ParamSpec, Self, TypeAlias, TypedDict
# --- Final and Literal -------------------------------------------------------------
MAX_LINES: Final = 50 # mypy: "Cannot assign to final name" on reassignment
Currency = Literal["EUR", "USD", "IRR"] # only these three strings type-check
OrderStatus = Literal["pending", "paid", "shipped", "cancelled"]
# --- NewType: same runtime value, different static type -------------------------------
UserId = NewType("UserId", int)
OrderId = NewType("OrderId", int)
# --- TypeAlias (PEP 613). On 3.12+ write: type JSONValue = ... (PEP 695, lazily evaluated) --
JSONScalar: TypeAlias = Union[str, int, float, bool, None]
JSONValue: TypeAlias = Union[JSONScalar, Dict[str, "JSONValue"], list["JSONValue"]]
# --- TypedDict: the shape of a dict, checked statically, a plain dict at runtime -------
class _OrderRowRequired(TypedDict):
id: int
status: OrderStatus
class OrderRow(_OrderRowRequired, total=False):
# Optional keys. On 3.11+ write `note: NotRequired[str]` in one class (PEP 655); on 3.9
# with `from __future__ import annotations` the string "NotRequired[str]" is not seen
# by the TypedDict machinery, so the key would wrongly count as required.
note: str
# --- Protocol: structural subtyping ("if it has these methods, it fits") --------------
@runtime_checkable
class PaymentGateway(Protocol):
def charge(self, order_id: OrderId, amount_cents: int, currency: Currency) -> str: ...
class FakeGateway:
"""Never inherits from PaymentGateway, still satisfies it."""
def __init__(self) -> None:
self.calls: list[tuple[OrderId, int, Currency]] = []
def charge(self, order_id: OrderId, amount_cents: int, currency: Currency) -> str:
self.calls.append((order_id, amount_cents, currency))
return f"ch_{order_id}"
def checkout(gateway: PaymentGateway, order_id: OrderId, amount_cents: int) -> str:
return gateway.charge(order_id, amount_cents, "EUR")
# --- Generic + TypeVar: a container that keeps the element type -----------------------
T = TypeVar("T")
@dataclass
class Page(Generic[T]):
items: list[T]
total: int
next_cursor: str | None = None # fine on 3.9 thanks to the __future__ import
def first(self) -> T | None:
return self.items[0] if self.items else None
# --- Self (PEP 673): fluent builders keep the subclass type ----------------------------
@dataclass
class QueryBuilder:
filters: list[str] = field(default_factory=list)
def where(self, clause: str) -> Self:
self.filters.append(clause)
return self
class OrderQuery(QueryBuilder):
def paid(self) -> Self:
return self.where("status = 'paid'")
# --- ParamSpec (PEP 612): a decorator that keeps the wrapped signature -----------------
P = ParamSpec("P")
R = TypeVar("R")
def timed(fn: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
wrapper.last_ms = (time.perf_counter() - start) * 1000 # type: ignore[attr-defined]
return wrapper
@timed
def order_total(prices_cents: Iterable[int], discount_cents: int = 0) -> int:
return sum(prices_cents) - discount_cents
# --- overload: one function, several precise signatures --------------------------------
@overload
def find_order(order_id: OrderId) -> OrderRow | None: ...
@overload
def find_order(order_id: OrderId, *, required: Literal[True]) -> OrderRow: ...
def find_order(order_id: OrderId, *, required: bool = False) -> OrderRow | None:
row: Optional[OrderRow] = {"id": order_id, "status": "paid"} if order_id == 1 else None
if row is None and required:
raise LookupError(order_id)
return rowType hints, gradual typing and static checkers (mypy, pyright) Must-know
In plain words: A type hint is a note next to a name: qty: int, def total(prices: list[int]) -> int. Python stores the note and carries on. A type checker (mypy, pyright) reads every note in the project without running it and reports places where the notes contradict each other. "Gradual" means you can add notes one function at a time; unannotated code is treated as "anything goes".
Common misunderstanding: "If mypy passes, the types are right at runtime." mypy proves consistency between annotations, not facts about data: a dict[str, Any] from json.loads is "anything", and Any switches checking off (the snippet's before.py passes mypy --strict with dict[str, Any] and checks nothing). Data from outside needs runtime validation. The reverse also bites: mypy "will not type check dynamically typed functions" by default, so a function without annotations is never checked unless you pass --check-untyped-defs (pyright checks them by default).
Definition: PEP 484 defines the semantics; the typing docs state "The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc." mypy's docs: "Mypy is designed to support gradual typing, i.e. letting you add annotations at your own pace". pyright's comparison page: "By default, pyright performs type checking for all code regardless of whether it contains type annotations" while "By default, mypy skips all functions or methods that do not have type annotations."
developer mypy 1.19.1 --strict (real run) runtime (CPython 3.9.6)
1 checkout(FakeGateway(), user, 100)
2 error: Argument 2 to "checkout" has
incompatible type "UserId"; expected
"OrderId" [arg-type]
3 row = find_order(order_id); row["status"]
4 error: Value of type "Optional[OrderRow]"
is not indexable [index]
5 annotations_are_not_enforced("ab") returns "abab", no error
6 CI fails at step 2/4, before deploy step 5 is what production sees without CIReal scenario: a refactor renames Order.total_cents to Order.total and mypy lists the 14 call sites in seconds; a function returns None on a cache miss and the checker forces every caller to handle it; an editor (Pylance in VS Code uses pyright's settings) autocompletes model fields because they are typed; a legacy module is added to the checker with per-module ignore_errors and tightened over months.
| mypy | pyright | |
|---|---|---|
| Origin | The checker the PEP 484 era grew up with | Microsoft; its configuration docs describe the same settings in Pylance (VS Code) |
| Unannotated functions | Skipped unless --check-untyped-defs | Checked by default |
| Strict switch | strict = true in [tool.mypy] | typeCheckingMode = "strict" |
| Pydantic support | pydantic.mypy plugin (plugins = ["pydantic.mypy"], used in the snippet) | No plugin; the Pydantic docs say models integrate "with static typing tools (like mypy and Pyright)" |
| Version used here | 1.19.1 (latest 2.4.1 needs Python ≥ 3.10) | Not installed on the build machine, not run |
| Error codes | [arg-type], [index], [misc], [union-attr] … | reportArgumentType, reportOptionalSubscript … |
Fix / how to use it: annotate every public function and every model, run the checker in CI in strict mode on new code, and keep Any at the edges only (immediately validated by Pydantic). The real run: tests/test_static_typing.py runs mypy on app/static_errors.py and asserts the four findings (arg-type twice, index, misc), then runs it on the rest of app/ and asserts Success: no issues found in 12 source files.
"""Wrong on purpose: every function here runs without an error at runtime,
and mypy reports each one. tests/test_static_typing.py runs both and compares."""
from __future__ import annotations
from typing import Final
from app.typing_toolbox import FakeGateway, OrderId, UserId, checkout, find_order
RETRIES: Final = 3
def wrong_argument_type() -> int:
return len(42) # type: ignore[arg-type] # silenced: shows how an ignore looks
def passes_user_id_as_order_id(user: UserId) -> str:
return checkout(FakeGateway(), user, 100) # mypy: UserId is not OrderId (NewType)
def optional_not_checked(order_id: OrderId) -> str:
row = find_order(order_id)
return row["status"] # mypy: row may be None
def wrong_literal() -> str:
return FakeGateway().charge(OrderId(1), 100, "GBP") # mypy: not one of the Literal values
def reassign_final() -> None:
global RETRIES
RETRIES = 4 # mypy: cannot assign to a Final name
def annotations_are_not_enforced(x: int) -> int:
return x * 2 # called with "ab" at runtime it returns "abab"Optional, Union, X | None and from __future__ import annotations Must-know
In plain words: Optional[int] means "an int or None", nothing more; on Python 3.10+ you write it int | None (PEP 604). Union[int, str] / int | str is "either". from __future__ import annotations makes Python store every annotation as a string instead of evaluating it, which lets you write int | None in annotations even on 3.9, and lets classes refer to themselves before they exist.
Common misunderstanding: "Optional means the field may be omitted." It means the value may be None; whether it may be omitted depends on a default. coupon: str | None with no default is required in Pydantic (you must send null); coupon: str | None = None is optional. Second misunderstanding: "the future import is harmless." Anything that evaluates annotations at runtime (Pydantic, FastAPI, SQLAlchemy, dataclasses with InitVar) now has to find each name by string, and fails when it cannot.
Definition: PEP 604: "Allow writing union types as X | Y" (Python 3.10). PEP 563 (Python 3.7) stores annotations as strings; it is now marked "Superseded" (by PEP 649/749 in 3.14, where annotations are evaluated lazily by default). On 3.9 int | None as an expression raises TypeError: unsupported operand type(s) for |: 'type' and 'NoneType' (real run), so module-level aliases and TypeAdapter(...) arguments need Optional[...]/Union[...] there; inside annotations Pydantic needs eval-type-backport to evaluate the strings.
module with `from __future__ import annotations` (real runs, Pydantic 2.13.5, FastAPI 0.128.8)
1 if TYPE_CHECKING: from app.models import Money # moved there by a linter rule
2 class Invoice(BaseModel): total: Money # annotation is the string "Money"
3 Pydantic: cannot resolve "Money" -> Invoice.__pydantic_complete__ is False
4 Invoice.model_validate(...) -> PydanticUserError: `Invoice` is not fully defined; you should define `Money`, then call `Invoice.model_rebuild()`
5 FastAPI route `def charge(amount: Money)` with the same import: no import error, but POST /charge -> 422
{"type":"missing","loc":["query","amount"]} and GET /openapi.json -> 500
6 FastAPI route using a model defined inside a function (build_app): POST /bad -> 422 loc ["query","item"]Real scenario: Ruff's flake8-type-checking rule TC001 moves an import "only used for type annotations" under if TYPE_CHECKING: and the model breaks; its docs warn "If a class requires that type annotations be available at runtime (as is the case for Pydantic, SQLAlchemy, and other libraries), consider using the lint.flake8-type-checking.runtime-evaluated-base-classes and lint.flake8-type-checking.runtime-evaluated-decorators settings". A FastAPI app builds routes inside a factory function with a locally defined model, and the body silently becomes a required query parameter. A team on 3.9 writes Payment = Annotated[Card | Bank, ...] at module level and the import fails.
| Spelling | 3.9 | 3.10+ | 3.14 | Note |
|---|---|---|---|---|
Optional[int] | Yes | Yes | Yes | Still valid; X | None preferred |
int | None in an annotation | Only with the future import (and eval-type-backport for Pydantic) | Yes | Yes | |
int | None as an expression (alias, isinstance, TypeAdapter) | TypeError | Yes | Yes | Real run on 3.9.6 |
list[int] (PEP 585) | Yes | Yes | Yes | List[int] deprecated alias |
from __future__ import annotations | Strings | Strings | Deprecated, still works | Removal not before 3.13 end of life (2029) |
Forward reference "Order" | Quotes | Quotes | Not needed (deferred evaluation) |
Fix / how to use it: on 3.12+ write X | None and do not add the future import to modules that define Pydantic models or FastAPI routes unless you need it; if you have it, keep runtime-needed imports outside TYPE_CHECKING (configure Ruff's runtime-evaluated-base-classes = ["pydantic.BaseModel"]), define models at module level, and call Model.model_rebuild() after late definitions. The trap is reproduced in app/future_trap.py and app/fastapi_trap.py:
"""The `from __future__ import annotations` trap: an import moved under TYPE_CHECKING.
Linters (Ruff's flake8-type-checking rules, TC001-TC003) suggest moving imports that
are "only used in annotations" under `if TYPE_CHECKING:`. For a type checker that is
fine; for Pydantic (and FastAPI) the annotation is needed at runtime, so the model
cannot be built until the name exists and model_rebuild() is called.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic import BaseModel
if TYPE_CHECKING:
from app.models import Money
class Invoice(BaseModel):
number: str
total: Money # the string "Money" cannot be resolved when the class is created"""The `from __future__ import annotations` trap and the 3.9 TypedDict rule, as real errors."""
from __future__ import annotations
import typing
import pytest
from pydantic import BaseModel, PydanticUserError, TypeAdapter
def test_type_checking_import_breaks_the_model() -> None:
from app import future_trap
assert future_trap.Invoice.__pydantic_complete__ is False # Pydantic deferred the build
with pytest.raises(PydanticUserError, match="`Invoice` is not fully defined; you should define `Money`"):
future_trap.Invoice.model_validate({"number": "A-1", "total": {"amount": "1"}})
from app.models import Money
future_trap.Invoice.model_rebuild(_types_namespace={"Money": Money}) # the fix (or a real import)
assert future_trap.Invoice.model_validate({"number": "A-1", "total": {"amount": "1"}}).total.amount == 1
def test_frame_locals_are_captured_at_class_creation() -> None:
# Pydantic resolves names from the defining frame; a name defined later is missing.
class Outer(BaseModel):
inner: Inner
assert Outer.__pydantic_complete__ is False
class Inner(BaseModel):
x: int
Outer.model_rebuild() # now Inner exists in this frame
assert Outer.model_validate({"inner": {"x": "1"}}).inner.x == 1
def test_typing_typeddict_rejected_before_312() -> None:
class Row(typing.TypedDict):
sku: str
import sys
if sys.version_info >= (3, 12): # pragma: no cover
assert TypeAdapter(Row).validate_python({"sku": "a"}) == {"sku": "a"}
else:
with pytest.raises(PydanticUserError, match="typing_extensions.TypedDict"):
TypeAdapter(Row)
def test_pep604_at_runtime_fails_on_39() -> None:
import sys
if sys.version_info < (3, 10):
with pytest.raises(TypeError, match="unsupported operand"):
eval("int | None")"""The same trap inside FastAPI (optional extra: pip install '.[fastapi]').
With `from __future__ import annotations`, FastAPI reads `item: Item` as the
string "Item" and resolves it against the module globals. A model defined inside
a function is not there, so FastAPI cannot see that it is a Pydantic model and
treats the parameter as a required QUERY parameter: every request gets a 422.
"""
from __future__ import annotations
from typing import Any
from fastapi import FastAPI
from pydantic import BaseModel
class GoodItem(BaseModel): # module level: resolvable
name: str
def build_app() -> FastAPI:
app = FastAPI()
class Item(BaseModel): # function level: NOT resolvable from the string "Item"
name: str
@app.post("/bad")
def bad(item: Item) -> dict[str, Any]:
return {"name": item.name}
@app.post("/good")
def good(item: GoodItem) -> dict[str, Any]:
return {"name": item.name}
return appLiteral, Final and NewType Important
In plain words: Literal["EUR", "USD", "IRR"] is a type with exactly those values. Final marks a name that must never be reassigned. NewType("UserId", int) makes a type that is an int at runtime but a different type for the checker, so a user id cannot be passed where an order id is expected.
Common misunderstanding: "Final makes a constant" or "NewType creates a class." Neither does anything at runtime: tt.UserId(5) == 5 and type(uid) is int (asserted), and reassigning a Final only fails in mypy (Cannot assign to final name "RETRIES" [misc], real run). Literal is different in Pydantic: a Literal field is validated at runtime (error type literal_error, e.g. Input should be 'visa' or 'mastercard').
Definition: PEP 586 (Literal, 3.8), PEP 591 (Final, 3.8), typing.NewType (added in 3.5.2 per the typing docs). In Pydantic, Literal is the cheapest way to declare an enumerated string, and a Literal field is what a discriminated union uses as its tag.
static (mypy) runtime (Python) runtime (Pydantic)
1 charge(OrderId(1), 100, "GBP") -> [arg-type] error runs, returns "ch_1" Card(brand="amex") -> literal_error
2 RETRIES = 4 after RETRIES: Final = 3 -> [misc] reassigns silently n/a
3 checkout(gw, UserId(5), 100) -> [arg-type] runs: UserId(5) is int 5 validated as intReal scenario: order status as Literal["pending", "paid", "shipped", "cancelled"] mirrored by a SQL CHECK constraint (the snippet's storage.py); currency codes; NewType ids that stop "user 5's orders" being fetched with an order id; Final limits such as MAX_LINES.
| Construct | Static effect | Python runtime | Pydantic |
|---|---|---|---|
Literal["a", "b"] | Only those values type-check | Nothing | literal_error for other values; JSON Schema enum |
Final | No reassignment, no override | Nothing | a: Final = 1 in a model is a class variable, not a field, with PydanticDeprecatedSince211 ("it will be considered as a normal field in V3"); real run |
NewType("UserId", int) | Distinct type | Identity function | Validated as the base type |
Enum / str, Enum | Members only | Real objects | Validated; strict mode wants the member (is_instance_of) |
Fix / how to use it: Literal for small closed sets that are plain strings on the wire, Enum when the values need behaviour or are reused across modules, NewType for ids that are easy to mix up, Final for module constants; let the checker enforce the last two.
TypedDict Important
In plain words: A TypedDict describes a dict with known keys and value types, for code that keeps working with dicts (JSON rows, **kwargs, legacy APIs) instead of classes.
Common misunderstanding: "A TypedDict is a lightweight model." At runtime it is a plain dict (type(row) is dict, asserted) and nothing is checked, unless you pass it through Pydantic: TypeAdapter(list[StockRow]).validate_json(...) validates and returns plain dicts. Two 3.9 traps, both real runs: Pydantic rejects typing.TypedDict before 3.12 (PydanticUserError asking for typing_extensions.TypedDict), and NotRequired[...] written under from __future__ import annotations is not seen on 3.9, so the key counts as required (the snippet uses a total=False subclass instead).
Definition: PEP 589 (3.8); PEP 655 Required/NotRequired (3.11); PEP 705 ReadOnly (3.13). __required_keys__ and __optional_keys__ expose the shape at runtime. The Pydantic performance page: "With a simple benchmark, TypedDict is about ~2.5x faster than nested models".
1 row: OrderRow = {"id": 1, "status": "paid"} mypy: ok; missing "id" would be [typeddict-item]
2 type(row) is dict True: no class at runtime
3 STOCK.validate_json('[{"sku":"ABC-1234","on_hand":"7"}]')
4 -> [{"sku": "ABC-1234", "on_hand": 7}] (plain dicts, "7" -> 7)Real scenario: rows from a raw SQL query passed between functions; a JSON config with optional keys; the inner rows of a large report validated with a TypeAdapter (cheaper than nested models); typed **kwargs with Unpack[Options].
| Need | TypedDict | BaseModel |
|---|---|---|
| Runtime type | dict | Model instance |
| Validation | Only via TypeAdapter / as a field | Always |
| Methods, computed fields | No | Yes |
| Speed of validation | Faster (no instance creation) | Slower |
| Optional keys | total=False / NotRequired | Defaults |
Fix / how to use it: import TypedDict from typing_extensions on Python < 3.12 when Pydantic will see it; use it for high-volume inner rows and dict-shaped legacy data, models for anything with behaviour or aliases.
Protocol and structural subtyping Must-know
In plain words: A Protocol says "anything with these methods will do". The class that satisfies it does not inherit from it or even know it exists; the checker compares shapes. It is Go's interface model inside Python.
Common misunderstanding: "A Protocol is an abstract base class." An ABC is nominal (you must inherit or register); a Protocol is structural. And @runtime_checkable does not make isinstance check signatures: it only checks that the method names exist.
Definition: PEP 544, "Protocols: Structural subtyping (static duck typing)". mypy's docs: "Structural subtyping is based on the operations that can be performed with an object. Class Dog is a structural subtype of class Animal if the former has all attributes and methods of the latter, and with compatible types."
1 class PaymentGateway(Protocol): def charge(self, order_id, amount_cents, currency) -> str: ...
2 class FakeGateway: def charge(...) -> str # no base class
3 checkout(FakeGateway(), OrderId(7), 1250) # mypy: ok (shapes match); runtime: "ch_7"
4 isinstance(FakeGateway(), PaymentGateway) # True with @runtime_checkable (names only)
5 PaymentGateway in type(gw).__mro__ # False: no inheritance involvedReal scenario: a payment service depends on PaymentGateway and tests pass a fake; a repository Protocol lets SQLAlchemy and in-memory implementations swap; a cache client Protocol covers Redis and a dict; third-party classes you cannot change satisfy your Protocol automatically. This is the Dependency Inversion Principle (SOLID).
Protocol | abc.ABC | Go interface | |
|---|---|---|---|
| Satisfied by | Matching shape | Inheritance or register() | Matching method set |
| Checked | Statically | At instantiation (abstract methods) | At compile time |
Runtime isinstance | Only with @runtime_checkable, names only | Yes | Type assertion |
| Pydantic field type | Needs arbitrary_types_allowed and validates nothing structural | Same | n/a |
Fix / how to use it: define Protocols where they are consumed (the service module), keep them small, and type parameters with them; do not use them as Pydantic field types (Pydantic validates data, not behaviour).
Generics, TypeVar, ParamSpec, Self and overload Important
In plain words: TypeVar and Generic[T] let a container or function keep the element type (Page[int].first() returns int | None). ParamSpec lets a decorator keep the wrapped function's exact parameters. Self says "returns an instance of whatever subclass this was called on". @overload gives one function several precise signatures.
Common misunderstanding: "@overload dispatches at runtime." The overload stubs exist only for the checker; the last undecorated def is the one that runs (the snippet's find_order test calls all three paths). And on 3.9 typing.get_overloads() does not exist (3.11+), so the stubs are not even introspectable there.
Definition: PEP 484 (TypeVar, Generic, overload), PEP 612 (ParamSpec, 3.10), PEP 673 (Self, 3.11: "The new Self annotation provides a simple and intuitive way to annotate methods that return an instance of their class"), PEP 695 (3.12: def first[T](xs: list[T]) -> T, class Page[T]: ...), PEP 696 (3.13: type-parameter defaults). On 3.9 ParamSpec and Self come from typing_extensions.
1 @timed (Callable[P, R] -> Callable[P, R])
2 def order_total(prices_cents: Iterable[int], discount_cents: int = 0) -> int
3 order_total([100, 250], discount_cents=50) -> 300; mypy still knows the parameter names and types
4 OrderQuery().where("id > 10").paid() -> OrderQuery (Self), not QueryBuilder
5 find_order(OrderId(1), required=True) -> mypy: OrderRow (2nd overload), no None check neededReal scenario: Page[T] / Result[T] response wrappers, a retry or timing decorator that must not erase signatures, fluent query builders, find(id) -> Row | None vs get(id) -> Row signatures, generic repositories Repository[Order].
| Feature | 3.9 spelling | 3.12+ spelling |
|---|---|---|
| Type variable | T = TypeVar("T") | def f[T](x: T) -> T |
| Generic class | class Page(Generic[T]) | class Page[T] |
| Bounded | TypeVar("N", bound=Number) | [N: Number] |
| ParamSpec | typing_extensions.ParamSpec | def deco[**P, R](f: Callable[P, R]) |
| Self | typing_extensions.Self | typing.Self (3.11+) |
| Generic Pydantic model | class Page(BaseModel, Generic[T]) | class Page[T](BaseModel) |
Fix / how to use it: use Generic models for response envelopes, ParamSpec in every decorator you write, Self for builders and classmethod constructors, and @overload only where a flag changes the return type.
TypeAlias and the type statement Good to know
In plain words: An alias gives a long type a short name. JSONValue: TypeAlias = Union[...] (3.10) marks it explicitly; type JSONValue = ... (3.12) is a statement that also evaluates lazily, so recursive aliases need no quotes.
Common misunderstanding: "A type alias is a new type." It is the same type under another name (that is NewType's job). And a type statement alias is a TypeAliasType object, not the aliased type, so code that inspects it (or old library versions) must unwrap .__value__; current Pydantic accepts it.
Definition: PEP 613 (TypeAlias, 3.10); PEP 695 (type statement, 3.12): "the PEP introduces a new way to declare type aliases using the type statement, which creates an instance of TypeAliasType".
# Python 3.12+ only (expected, not run: the build machine has 3.9; this is a SyntaxError there)
type JSONValue = str | int | float | bool | None | dict[str, JSONValue] | list[JSONValue]
type Payment = Annotated[Card | BankTransfer | Wallet, Field(discriminator="kind")]
class Page[T](BaseModel): # PEP 695 generic model, no TypeVar needed
items: list[T]
next_cursor: str | None = None1 3.9: JSONValue: TypeAlias = Union[JSONScalar, Dict[str, "JSONValue"], list["JSONValue"]] # quotes for recursion
2 3.12: type JSONValue = ... | dict[str, JSONValue] # lazy, no quotes
3 type(JSONValue) -> typing.TypeAliasType; JSONValue.__value__ -> the unionReal scenario: a JSONValue alias for arbitrary JSON columns; Payment as a named discriminated union used in three models; an OrderId alias where NewType would be too strict for a gradual migration.
| Form | Since | Lazy | Recursive without quotes |
|---|---|---|---|
X = Union[...] | 3.5 | No | No |
X: TypeAlias = ... | 3.10 | No | No |
type X = ... | 3.12 | Yes | Yes |
Fix / how to use it: on 3.12+ prefer the type statement for new aliases; keep plain assignment for Annotated aliases that must also work on older interpreters.
Annotated and its metadata Must-know
In plain words: Annotated[int, Field(gt=0)] is the type int with an attached note that only interested tools read. The checker sees int; Pydantic sees int plus "greater than 0"; FastAPI sees Query(...) or Depends(...) in the same slot.
Common misunderstanding: "Metadata order does not matter." For Pydantic it does: the docs say "before and wrap validators are run from right to left, and after validators are then run from left to right", while Field constraints apply to the core step in between. In the snippet Sku = Annotated[str, AfterValidator(_check_sku), BeforeValidator(_normalise_sku)] first strips and upper-cases, then checks the pattern.
Definition: PEP 593: "This PEP introduces a mechanism to extend the type annotations from PEP 484 with arbitrary metadata."; What's New 3.9: "typing.Annotated type to decorate existing types with context-specific metadata and new include_extras parameter to typing.get_type_hints() to access the metadata at runtime".
1 Sku = Annotated[str, AfterValidator(_check_sku), BeforeValidator(_normalise_sku)]
2 input " abc-1234"
3 BeforeValidator -> "ABC-1234"
4 core str check -> ok
5 AfterValidator -> SKU_RE matches -> "ABC-1234"
6 input "bad" -> AfterValidator raises ValueError -> error type value_error at ("lines", 1, "sku")Real scenario: one Sku, Qty, Note, Flag alias reused in every model; Annotated[int, Field(ge=1, le=100), Query()] in FastAPI; Annotated[Session, Depends(get_session)] for dependencies; Annotated[str, Strict()] for one strict field.
| Metadata | Read by | Effect |
|---|---|---|
Field(gt=0, max_length=...) | Pydantic | Constraints, aliases, defaults, docs |
AfterValidator(f) / BeforeValidator(f) / WrapValidator(f) / PlainValidator(f) | Pydantic | Validation steps |
PlainSerializer(f) / WrapSerializer(f) | Pydantic | Serialisation steps |
Strict() | Pydantic | Strict mode for this type |
Discriminator(...), Tag(...) | Pydantic | Tagged unions |
Query(), Path(), Body(), Header(), Depends() | FastAPI | Parameter source and dependencies |
Mapped[...] annotations | SQLAlchemy 2 / SQLModel | Column types from annotations (SQLAlchemy 2 & SQLModel) |
Fix / how to use it: build a small vocabulary of Annotated aliases per domain (ids, money, codes) and reuse it; keep each alias's metadata in the order "constraints, after-validators, before-validators" so the reading order matches the execution order.
Five ways to declare a record: dataclass, NamedTuple, TypedDict, attrs, Pydantic Important
In plain words: All five generate the boilerplate of a record class. Only Pydantic converts and validates input; the stdlib options and attrs trust whoever calls them, attrs lets you opt into per-field validators and converters.
Common misunderstanding: "A @dataclass checks its field types." The docs: "With two exceptions described below, nothing in @dataclass examines the type specified in the variable annotation." LineDC("x", "2").qty == "2" (asserted). attrs is not a validation library either, in its own words: "attrs emphatically does not try to be a validation library, but a toolkit to write well-behaved classes", while its docs describe Pydantic as "first and foremost a data validation & type coercion library".
Definition: dataclasses (3.7), typing.NamedTuple (tuple subclass), TypedDict (dict), attrs (third party, @attrs.define/@attrs.frozen, attrs.field(validator=..., converter=...)), Pydantic BaseModel (and pydantic.dataclasses.dataclass, a stdlib-compatible dataclass with Pydantic validation).
"""The same record five ways: dataclass, NamedTuple, attrs, TypedDict and Pydantic.
Only Pydantic converts and validates input; the others trust their caller.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import NamedTuple
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import TypedDict
@dataclass(frozen=True)
class LineDC: # stdlib: __init__, __repr__, __eq__ generated; no conversion, no checks
sku: str
qty: int
class LineNT(NamedTuple): # a tuple with names: immutable, indexable, unpackable
sku: str
qty: int
class LineTD(TypedDict): # only a static shape: at runtime it is a plain dict
sku: str
qty: int
class LineModel(BaseModel): # parses, converts, validates, serialises, emits JSON Schema
model_config = ConfigDict(frozen=True)
sku: str = Field(min_length=3)
qty: int = Field(gt=0)
try: # attrs is an optional dev dependency; tests skip the attrs row without it
import attrs
@attrs.frozen
class LineAttrs: # attrs: validators and converters are opt-in, per field
sku: str = attrs.field(validator=attrs.validators.min_len(3))
qty: int = attrs.field(converter=int, validator=attrs.validators.gt(0))
except ImportError: # pragma: no cover
LineAttrs = None # type: ignore[assignment,misc] input sku="x", qty="2" result (real run)
1 LineDC("x", "2") LineDC(sku='x', qty='2') no check
2 LineNT("x", "2") ('x', '2') no check
3 LineTD {"sku": "x", "qty": "2"} plain dict
4 LineAttrs("x", "2") ValueError from min_len(3) qty converted by converter=int
5 LineModel(sku="x", qty="2") ValidationError string_too_short; with sku="ABC": qty=2Real scenario: dataclasses for domain objects and internal value types; NamedTuple for small immutable results that are unpacked (lat, lng = point); TypedDict for dict-shaped data; attrs where slots, validators and speed matter without a wire format; Pydantic wherever data crosses a trust boundary (HTTP, queues, files, environment).
| dataclass | NamedTuple | TypedDict | attrs 26.1 | Pydantic v2 | |
|---|---|---|---|---|---|
| Validates types | No | No | No | Opt-in per field | Yes |
Converts "2" → 2 | No | No | No | Opt-in converter= | Yes (lax mode) |
| Immutable option | frozen=True | Always | No | @attrs.frozen | frozen=True |
| JSON in/out | asdict + json | _asdict | is a dict | cattrs | model_dump_json / model_validate_json |
| JSON Schema | No | No | Via Pydantic | No | Yes |
| Runtime cost | Lowest | Lowest | None | Low | Validation on every instance |
Fix / how to use it: Pydantic at the edges, dataclasses (or attrs) in the core; see DTO vs domain object.
BaseModel and pydantic-core (Rust) Must-know
In plain words: You subclass BaseModel and list fields as annotations. When the class is created, Pydantic turns those annotations into a "core schema" and hands it to pydantic-core, a Rust library, which compiles a validator and a serialiser. Every OrderIn(...) or OrderIn.model_validate(...) call runs that compiled validator.
Common misunderstanding: "Pydantic is slow because it is Python." The per-instance work is in Rust: the docs say "Pydantic’s core validation logic is implemented in a separate package (pydantic-core), where validation for most types is implemented in Rust." and "As a result, Pydantic is among the fastest data validation libraries for Python." What costs time is class creation (schema building) and anything you run in Python: your validators, wrap validators, TypeAdapter(...) built per call. Measured here: 4.8 µs to validate the fixture order from a dict, 66 µs to rebuild a TypeAdapter on every call versus 13 µs reusing one (tests/test_perf.py -s, real).
Definition: "Untrusted data can be passed to a model and, after parsing and validation, Pydantic guarantees that the fields of the resultant model instance will conform to the field types defined on the model." Fields are in Model.model_fields; set fields in m.model_fields_set; extras (with extra="allow") in m.model_extra. Validation runs on construction only: assignment is not validated unless validate_assignment=True (order.customer_email = 42 succeeds, asserted).
class creation (import time) per call (runtime)
1 class OrderIn(CamelModel): fields from annotations
2 resolve annotations (strings -> types; eval-type-backport on 3.9)
3 build core schema (Python) -> SchemaValidator + SchemaSerializer (Rust)
4 OrderIn.model_validate(payload)
5 Rust: walk the dict, coerce, check constraints,
call Python validators where declared
6 success: instance; failure: one ValidationErrorReal scenario: request bodies in FastAPI; messages consumed from Kafka or RabbitMQ; rows from a partner's CSV; responses from a third-party HTTP API called with httpx (validate before you trust them); LLM tool-call arguments.
| Method / attribute | Purpose |
|---|---|
Model(**kwargs) | Validate keyword arguments (by field name or alias) |
Model.model_validate(obj, strict=, from_attributes=, context=) | Validate a Python object |
Model.model_validate_json(text) | Parse + validate JSON in Rust |
Model.model_validate_strings(obj) | Validate a dict of strings (as if from JSON) |
Model.model_construct(**values) | No validation (trusted data) |
m.model_dump() / m.model_dump_json() | Serialise |
m.model_copy(update=...) | Copy; update is not validated (qty=-5 accepted, real run) |
Model.model_json_schema() | JSON Schema |
Model.model_fields, m.model_fields_set, m.model_extra | Introspection |
Model.model_rebuild() | Retry schema building after forward references resolve |
Fix / how to use it: one model per boundary shape, validated once at the boundary; never use model_construct on untrusted data (Money.model_construct(amount="not a number") happily stores the string, asserted); turn on validate_assignment only for models that are mutated after creation.
Lax mode, strict mode and the conversion table Must-know
In plain words: By default (lax mode) Pydantic converts obvious representations into the field type: "3" → 3, "yes" → True, "2026-11-29T10:00:00Z" → datetime. Strict mode accepts only values that already have the type, with exceptions for JSON, which has no date, Decimal, UUID or tuple types.
Common misunderstanding: "Lax mode converts anything." It converts only lossless, well-defined cases: 3.5 to int is int_from_float, "3.5" is int_parsing, "1e3" is int_parsing, 2 to bool is bool_parsing, and numbers to str are rejected (string_type) unless you set coerce_numbers_to_str=True (all real runs; the migration guide confirms "coercing int, float, and Decimal values to strings is now optional and disabled by default"). Surprises do exist: "3.0" and "3_000" are accepted as int (3 and 3000), and a date-only string "2026-11-29" becomes a midnight datetime without a timezone.
Definition: "When strict mode is enabled, Pydantic will be much less lenient when coercing data, and will instead error if the data is not of the correct type." "Most of the time, strict mode will only allow instances of the type to be provided, although looser rules may apply to JSON input (for instance, the date and time types allow strings even in strict mode)." The official conversion table lists every pair for "JSON", "JSON - Strict", "Python" and "Python - Strict". Strict mode is set per call (model_validate(x, strict=True)), per field (Field(strict=True), StrictInt, Annotated[int, Strict()]) or per model (ConfigDict(strict=True)).
LaxLine / StrictLine with {"qty": "3", "price": "9.99", "placed_at": "2026-11-29T10:00:00Z"} (real run)
1 LaxLine.model_validate(...) -> qty=3, price=Decimal('9.99'), placed_at=datetime(2026, 11, 29, 10, 0, tzinfo=UTC)
2 StrictLine.model_validate(...) -> 3 errors: int_type, is_instance_of (Decimal), datetime_type
3 StrictLine.model_validate_json(...) with qty as a JSON number -> ok: Decimal and datetime from JSON strings
4 LaxLine.model_validate(..., strict=True) -> fails like line 2: strictness is per call tooReal scenario: a payment amount field where "10" from a form must be accepted (lax) next to an internal event bus where a string id where an int is expected is a producer bug (strict); boolean feature flags from environment variables ("true", "1", "on" all accepted in lax mode); a partner API that sends numbers as strings.
The real coercion results (Pydantic 2.13.5, runs/p1_coercion-output.txt):
| Field type ← input | Lax, Python | Strict, Python | Lax, JSON | Strict, JSON |
|---|---|---|---|---|
int ← "3" | 3 | int_type | 3 | int_type |
int ← 3.0 | 3 | int_type | 3 | int_type |
int ← 3.5 | int_from_float | int_type | int_from_float | int_type |
int ← True | 1 | int_type | 1 | int_type |
int ← "3.0" | 3 | int_type | 3 | int_type |
float ← 1 | 1.0 | 1.0 | 1.0 | 1.0 |
float ← "nan" | nan | float_type | nan | float_type |
bool ← "yes", "on", "1", "y", 1 | True | bool_type | True | bool_type |
bool ← "maybe", 2 | bool_parsing | bool_type | bool_parsing | bool_type |
str ← 3 | string_type | string_type | string_type | string_type |
str ← b"ab" | "ab" | string_type | n/a | n/a |
Decimal ← "1.10" | Decimal('1.10') | is_instance_of | Decimal('1.10') | Decimal('1.10') |
datetime ← ISO string | datetime | datetime_type | datetime | datetime |
datetime ← unix seconds | datetime (UTC) | datetime_type | datetime | datetime_type |
datetime ← "2026-11-29" | naive midnight | datetime_type | naive midnight | datetime_parsing |
date ← "2026-11-29T00:00:00Z" | date | date_type | date | date_parsing |
UUID ← string | UUID | is_instance_of | UUID | UUID |
list[int] ← tuple or set | list | list_type | n/a | n/a |
tuple[int, ...] ← list | tuple | tuple_type | tuple | tuple |
Enum ← value | member | is_instance_of | member | member |
Fix / how to use it: keep lax mode at public HTTP boundaries (browsers and forms send strings) but declare precise types; use strict mode for internal contracts and for fields where conversion hides bugs (money, ids); never rely on lax datetime without requiring a timezone (the snippet's OrderIn rejects naive datetimes in its after validator; Pydantic also has AwareDatetime).
"""Lax mode (default) converts; strict mode accepts only the exact type (with JSON exceptions)."""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
import pytest
from pydantic import ValidationError
from app.models import LaxLine, StrictLine
PY_INPUT = {"qty": "3", "price": "9.99", "placed_at": "2026-11-29T10:00:00Z"}
JSON_INPUT = '{"qty": 3, "price": "9.99", "placed_at": "2026-11-29T10:00:00Z"}'
def test_lax_converts_strings() -> None:
line = LaxLine.model_validate(PY_INPUT)
assert (line.qty, line.price, line.placed_at.year) == (3, Decimal("9.99"), 2026)
def test_strict_rejects_strings_from_python() -> None:
with pytest.raises(ValidationError) as exc:
StrictLine.model_validate(PY_INPUT)
assert [e["type"] for e in exc.value.errors()] == ["int_type", "is_instance_of", "datetime_type"]
def test_strict_json_still_accepts_strings_for_decimal_and_datetime() -> None:
line = StrictLine.model_validate_json(JSON_INPUT) # JSON has no Decimal/datetime type
assert isinstance(line.price, Decimal) and isinstance(line.placed_at, datetime)
def test_strict_per_call() -> None:
with pytest.raises(ValidationError):
LaxLine.model_validate(PY_INPUT, strict=True)
@pytest.mark.parametrize(
("value", "expected"),
[
(3, 3),
("3", 3),
(" 3 ", 3),
("3.0", 3),
("3_000", 3000),
(3.0, 3),
(True, 1),
(b"3", 3),
(3.5, "int_from_float"),
("3.5", "int_parsing"),
("1e3", "int_parsing"),
(None, "int_type"),
],
)
def test_lax_int_rules(value: object, expected: object) -> None:
# Real 2.13.5 behaviour for an `int` field in lax mode (Python input).
if isinstance(expected, int):
assert LaxLine.model_validate({**PY_INPUT, "qty": value}).qty == expected
else:
with pytest.raises(ValidationError) as exc:
LaxLine.model_validate({**PY_INPUT, "qty": value})
assert exc.value.errors()[0]["type"] == expectedValidating input: model_validate, model_validate_json, model_construct Must-know
In plain words: model_validate(dict_or_object) validates Python data; model_validate_json(text_or_bytes) parses JSON and validates in one step inside Rust; model_construct(**values) skips validation for data you already trust.
Common misunderstanding: "json.loads then model_validate is the same thing." It produces the same model, but the Pydantic docs recommend the direct path: "In general, use model_validate_json() not model_validate(json.loads(...))", because "On model_validate(json.loads(...)), the JSON is parsed in Python, then converted to a dict, then it’s validated internally." Measured here for one order: 6.3 µs direct vs 6.8 µs two-step (real run; the gap grows with payload size). Strict mode also behaves differently on the JSON path (dates and decimals from strings are allowed).
Definition: BaseModel.model_validate(obj, *, strict=None, from_attributes=None, context=None, ...), model_validate_json(json_data, *, strict=None, context=None, ...), model_validate_strings(obj, ...); context is passed to validators as info.context.
1 body = request bytes
2 A: OrderIn.model_validate_json(body) -> Rust parser (jiter) + validator, one pass
3 B: OrderIn.model_validate(json.loads(body)) -> Python dict first, then validator
4 C: OrderIn.model_construct(**row) -> no checks: only for rows you wrote yourself
5 A and B both raise ValidationError; malformed JSON in A is error type json_invalidReal scenario: reading a JSON column back from the database (OrderStore.get uses model_validate_json); consuming a message body from a queue; re-hydrating cached responses from Redis (model_validate_json on the cached bytes); model_construct in a hot path that copies already-validated models.
| Input | Method | Notes |
|---|---|---|
dict, list, objects | model_validate | from_attributes=True for objects |
str / bytes JSON | model_validate_json | Fastest path, JSON strict rules |
dict[str, str] (form, query) | model_validate_strings | Treats values as JSON strings |
| Trusted values | model_construct | Sets model_fields_set, no validation |
| Many items | TypeAdapter(list[Model]).validate_json | One call for the whole array |
Fix / how to use it: feed bytes straight to model_validate_json; keep model_construct for data produced by your own code; pass request-scoped facts (tenant, current user) through context instead of globals.
Serialization: model_dump, model_dump_json and serializers Must-know
In plain words: model_dump() turns a model back into a dict, model_dump_json() straight into JSON text. Options decide which fields appear (include, exclude, exclude_unset, exclude_none, exclude_defaults) and under which names (by_alias). field_serializer and model_serializer customise how values or the whole model are written; computed_field adds read-only derived values.
Common misunderstanding: "model_dump() gives JSON-ready data." The default mode="python" keeps Decimal, datetime, UUID and custom objects (the snippet's Postcode stays a Postcode object in model_dump() and becomes "12345-67890" only in JSON mode, asserted). Use model_dump(mode="json") or model_dump_json(). Second one: "exclude_unset drops None." It drops fields the client never sent, even nested ones (unit_price without currency stays {'amount': '12.50'} in the real run); exclude_none drops None values.
Definition: the docs: "exclude_unset: Pydantic keeps track of fields that were explicitly set during instantiation (using the model_fields_set property). Using exclude_unset, any field that was not explicitly provided will be excluded". "The @computed_field decorator can be used to include properties (or cached properties) when serializing a model or dataclass. The property will also be included in the JSON Schema (in serialization mode)."
OrderIn validated from the fixture (real run)
1 order.model_dump(by_alias=True, mode="json", include={"customer_email", "placed_at"})
-> {"customerEmail": "ana@example.com", "placedAt": "2026-11-29T10:00:00+03:30"}
2 order.model_dump(exclude_unset=True) -> no "coupon", no "note" (client never sent them)
3 order.model_dump(exclude_none=True) -> no "coupon" (it is None)
4 order.lines[0].model_dump(by_alias=True)["lineTotal"] -> {"amount": "25.00", "currency": "EUR"} (computed_field)
5 Money amount -> "12.50" (field_serializer: never a float in JSON)
6 Page[int](items=[1, 2], total=2).model_dump() -> {..., "count": 2} (model_serializer mode="wrap")Real scenario: a PATCH /orders/{id} handler applies payload.model_dump(exclude_unset=True) so omitted fields keep their values; money is serialised as a string so JavaScript clients do not lose cents; timestamps are normalised to UTC with a Z (OrderOut._utc_z); an envelope adds a count key; a password_hash field is excluded with Field(exclude=True).
| Option / tool | Effect |
|---|---|
mode="python" / "json" | Python objects vs JSON-compatible values |
by_alias=True (or serialize_by_alias=True config, 2.11+) | Use aliases (customerEmail) |
include / exclude (sets or nested dicts) | Pick fields, e.g. exclude={"lines": {"all": {"line_total"}}} |
exclude_unset | Only fields that were provided |
exclude_defaults | Drop fields equal to their default |
exclude_none | Drop None values |
Field(exclude=True) | Never serialise this field |
@field_serializer("x") | Custom output for one field (mode="plain" or "wrap") |
@model_serializer | Custom output for the whole model (mode="plain" or "wrap") |
PlainSerializer / WrapSerializer in Annotated | Reusable serialisers |
@computed_field | Property included in dumps and the serialization JSON Schema; ignored on input |
Fix / how to use it: return the JSON from model_dump_json() (a str; TypeAdapter.dump_json() returns bytes, and the docs explain that "in V1, model dumping returned a str type, so this behavior is retained in V2 for backwards compatibility"; real run: str vs bytes) or let FastAPI do it via response_model, use exclude_unset for partial updates, never let a float carry money, and keep secrets out with Field(exclude=True) or a separate output model.
Aliases: alias, validation_alias, serialization_alias, alias_generator Must-know
In plain words: The wire uses one name (customerEmail), Python another (customer_email). An alias maps them. alias sets both directions, validation_alias only the input name (or several, with AliasChoices), serialization_alias only the output name, and alias_generator=to_camel generates aliases for every field.
Common misunderstanding: "Setting alias_generator on the parent model covers nested models." model_config is per class: the first run of the snippet failed with lines.0.unit_price Field required because OrderLine had no generator; the fix is a shared base class (CamelModel). Second: "with an alias, the Python name also works." Only with populate_by_name=True (in 2.11+ validate_by_name=True; on 2.13.5 setting populate_by_name=True also sets validate_by_name and validate_by_alias to True, real run). Third: aliases are used on output only with by_alias=True or serialize_by_alias=True.
Definition: Field(alias=..., validation_alias=..., serialization_alias=...), AliasChoices("placedAt", "placed_at", "createdAt"), AliasPath("data", 0, "id"), ConfigDict(alias_generator=to_camel) (also to_snake, to_pascal in pydantic.alias_generators, or an AliasGenerator with separate validation/serialization functions). The config docs: "populate_by_name usage is not recommended in v2.11+ and will be deprecated in v3. Instead, you should use the validate_by_name configuration setting."
OrderIn (CamelModel: alias_generator=to_camel, populate_by_name=True) real runs
1 {"customerEmail": ...} -> customer_email (alias)
2 {"customer_email": ...} -> customer_email (populate_by_name)
3 {"createdAt": ...} -> placed_at (validation_alias=AliasChoices(...))
4 model_dump() -> {"customer_email": ...}
5 model_dump(by_alias=True) -> {"customerEmail": ...}
6 JSON Schema properties -> "customerEmail", "placedAt" (first AliasChoices entry)Real scenario: a JavaScript frontend that speaks camelCase; a partner whose API renamed created to createdAt (accept both with AliasChoices during the migration); a nested envelope read with AliasPath("data", "attributes", "email"); a field whose wire name is a Python keyword (from, class).
| Need | Use |
|---|---|
| Same alias in and out | Field(alias="customerEmail") |
| Accept several input names | validation_alias=AliasChoices(...) |
| Read a nested key | validation_alias=AliasPath(...) |
| Different output name | serialization_alias=... |
| camelCase everywhere | alias_generator=to_camel on a shared base |
| Accept Python names too | validate_by_name=True (2.11+) / populate_by_name=True |
| Output by alias by default | serialize_by_alias=True (2.11+) |
Fix / how to use it: put alias_generator, validate_by_name (or populate_by_name on older versions) and, on 2.11+, serialize_by_alias on one base model for the whole API, and test one nested model explicitly.
Field and constraints Must-know
In plain words: Field(...) attaches rules and metadata to one field: numeric bounds, string and list lengths, a regex pattern, decimal precision, a default or default factory, an alias, a description and examples for the docs.
Common misunderstanding: "Field(pattern=...) uses Python's re." Pydantic v2 uses the Rust regex crate by default, which has no look-arounds or back-references: Field(pattern=r"^(?=.*\d).{8,}$") fails at class creation with SchemaError: Error building "model" validator (real run); ConfigDict(regex_engine="python-re") switches engines. Second: "a mutable default is shared between instances." Pydantic copies it (b.tags == [] after a.tags.append("x"), real run), but default_factory is still the clearer spelling.
Definition: the constraints gt ge lt le (gt, ge, lt, le, multiple_of) for numbers; min_length max_length for strings, lists, sets and dicts; pattern for strings; max_digits and decimal_places for Decimal; default, default_factory, alias*, title, description, examples, json_schema_extra, exclude, repr, frozen, strict, discriminator. The migration guide: Field constraints "are no longer automatically pushed down to the parameters of generics", so list[Annotated[str, Field(pattern=...)]] constrains each item.
Field rules in the snippet (real errors)
1 qty: Annotated[int, Field(gt=0, le=1000)] 0 -> greater_than; 1001 -> less_than_equal
2 amount: Decimal = Field(ge=0, max_digits=12, decimal_places=2) Decimal("1.999") -> decimal_max_places
3 lines: list[OrderLine] = Field(min_length=1, max_length=50) [] -> too_short
4 customer_email: str = Field(max_length=254, pattern=...) "x" -> string_pattern_mismatch
5 last4: str = Field(pattern=r"^\d{4}$") "12" -> string_pattern_mismatchReal scenario: quantity and price bounds on an order line; page size le=100; ISO country codes pattern=r"^[A-Z]{2}$"; Decimal money with two places; default_factory=datetime.now (never default=datetime.now(), which is evaluated once at import); examples=[...] that show up in Swagger UI.
| Constraint | Applies to | Error type |
|---|---|---|
gt / ge / lt / le | numbers, dates | greater_than, greater_than_equal, less_than, less_than_equal |
multiple_of | numbers | multiple_of |
min_length / max_length | str | string_too_short / string_too_long |
min_length / max_length | list, set, dict | too_short / too_long |
pattern | str | string_pattern_mismatch |
max_digits / decimal_places | Decimal | decimal_max_digits / decimal_max_places |
strict=True | any | int_type, string_type … |
frozen=True (field) | any | frozen_field on assignment |
Fix / how to use it: put constraints in reusable Annotated aliases, keep regexes compatible with the Rust engine (or switch the engine explicitly), and use default_factory for anything mutable or time-dependent.
Validators: field_validator, model_validator and the Annotated validators Must-know
In plain words: Validators are your own functions plugged into the validation pipeline. Field validators see one value, model validators the whole input or the whole instance. The mode before after wrap decides when they run: before the core type check (raw input), after it (typed value), or around it (with a handler to call). PlainValidator replaces the core check altogether.
Common misunderstanding: "A validator must return True or False." It returns the (possibly changed) value, and signals failure by raising ValueError or AssertionError (error type value_error / assertion_error) or a PydanticCustomError with your own type. Raising ValidationError yourself is wrong except inside wrap validators that re-raise. Second: "mode='after' model validators run even when fields failed." They do not; the instance does not exist yet.
Definition: from the docs: "After validators: run after Pydantic’s internal validation. They are generally more type safe and thus easier to implement." "Before validators: run before Pydantic’s internal parsing and validation (e.g. coercion of a str to an int)." "Plain validators: act similarly to before validators but they terminate validation immediately after returning, so no further validators are called and Pydantic does not do any of its internal validation against the field type." "Wrap validators: are the most flexible of all." For models: "After validators: run after the whole model has been validated. As such, they are defined as instance methods and can be seen as post-initialization hooks. Important note: the validated instance should be returned." v2 replaced v1's @validator and @root_validator (both deprecated, real PydanticDeprecatedSince20 warning).
OrderIn.model_validate(fixture + {"items": [...], "coupon": "", "note": "x"*250, "gift": "yes"}) real run
1 model_validator(mode="before") _accept_legacy_items: "items" -> "lines"
2 customer_email: core str + strip + pattern -> field_validator(after) _lower_email -> "ana@example.com"
3 coupon: field_validator(mode="before") "" -> None
4 note: WrapValidator _truncate: handler raises string_too_long -> handler(value[:200]) -> 200 chars
5 gift: PlainValidator _parse_flag: "yes" -> True ("true" -> "use yes or no")
6 lines[*].sku: BeforeValidator strip/upper -> core str -> AfterValidator pattern check
7 model_validator(mode="after") _one_currency: EUR + USD -> value_error "all lines must use one currency"Real scenario: normalising emails and phone numbers (after), turning empty strings from HTML forms into None (before), accepting a legacy payload shape during an API migration (model before), "end date after start date" and "one currency per order" (model after), a lenient parser that falls back to a default (wrap), a third-party format with its own parser (plain).
| Decorator / annotation | Signature | Sees | Use for |
|---|---|---|---|
@field_validator("f") (after) | (cls, value[, info]) classmethod | Typed value | Business rules on one field |
@field_validator("f", mode="before") | (cls, value[, info]) | Raw value | Normalising input |
@field_validator("f", mode="wrap") | (cls, value, handler[, info]) | Raw value + handler | Fallbacks |
@field_validator("f", mode="plain") | (cls, value[, info]) | Raw value | Replacing type rules |
AfterValidator(fn) etc. in Annotated | fn(value[, info]) | Same as above | Reusable across models |
@model_validator(mode="before") | (cls, data) classmethod | Raw input | Reshaping input |
@model_validator(mode="after") | (self) returns self | Instance | Cross-field rules |
@model_validator(mode="wrap") | (cls, data, handler) | Raw + handler | Logging, fallback models |
info: ValidationInfo | .data, .context, .field_name, .mode | Already-validated fields, context | Rules that depend on earlier fields |
Fix / how to use it: prefer after validators (typed, simple), before validators only for reshaping, wrap validators sparingly (the performance page: "Wrap validators are generally slower than other validators"), and cross-field rules in one model_validator(mode="after").
Discriminated unions: Field(discriminator=...), Discriminator and Tag Important
In plain words: When a field can hold one of several models (card, bank transfer, wallet), a "tag" field such as kind says which one it is. Telling Pydantic about the tag means it validates only that model, reports errors for that model only, and documents the choice in JSON Schema.
Common misunderstanding: "A plain Union picks the right model." In smart mode members are tried left to right and an exact type match returns at once ("If validation succeeds with an exact type match, that member is returned immediately and following members will not be attempted"), but a dict is never an exact match for a model, so model members are all tried and, on failure, every member's errors are reported: the same bad card payload gives 6 errors with a plain union (Card.brand, Card.last4, BankTransfer.kind, BankTransfer.iban, Wallet.kind, Wallet.provider) and 2 with a discriminator (("card", "brand"), ("card", "last4")), both real runs. The docs: "In general, we recommend using discriminated unions. They are both more performant and more predictable than untagged unions".
Definition: Annotated[Union[Card, BankTransfer, Wallet], Field(discriminator="kind")] where each member has kind: Literal["card"] etc.; or a callable Discriminator(fn) with members wrapped in Annotated[Card, Tag("card")], where fn(value) returns the tag (or None). Errors: union_tag_invalid (unknown tag), union_tag_not_found (no tag). Discriminated unions "are sometimes referred to as “Tagged unions”".
1 {"kind": "card", "brand": "visa", "last4": "4242"} -> Card
2 {"kind": "crypto"} -> union_tag_invalid, ctx {"discriminator": "'kind'", "tag": "crypto", "expected_tags": "'card', 'bank', 'wallet'"}
3 LegacyPayment {"last4": "4242", "brand": "visa"} -> _payment_tag -> "card" -> Card
4 LegacyPayment {"something": "else"} -> _payment_tag -> None -> union_tag_not_found
5 PAYMENT.json_schema()["discriminator"] -> {"propertyName": "kind", "mapping": {"card": "#/$defs/Card", ...}}Real scenario: payment methods; webhook events (type: "invoice.paid" vs "charge.refunded"); notification channels (email, SMS, push); shapes in a drawing app; LLM tool calls distinguished by tool name; a versioned message envelope with version: Literal[1] / Literal[2].
Plain Union (smart) | union_mode="left_to_right" | Field(discriminator=...) | Discriminator(callable) | |
|---|---|---|---|---|
| Members tried | All, best match wins | In order, first success | Exactly one | Exactly one |
| Errors on failure | Every member's | Every member's | The chosen member's | The chosen member's |
| Needs a tag field | No | No | Yes (Literal) | No (function decides) |
| JSON Schema | anyOf | anyOf | oneOf + discriminator mapping | oneOf |
| Speed | Grows with members | Grows with members | One lookup | One function call |
Fix / how to use it: add a Literal tag to every model that can appear in a union and declare the discriminator; for legacy data without a tag, use a callable Discriminator until producers send one.
"""Discriminated unions pick one model by a tag; plain unions try every member."""
from __future__ import annotations
from typing import Union
import pytest
from pydantic import TypeAdapter, ValidationError
from app.adapters import PAYMENT
from app.models import BankTransfer, Card, LegacyPayment, Wallet
PLAIN = TypeAdapter(Union[Card, BankTransfer, Wallet]) # smart mode, no discriminator
LEGACY = TypeAdapter(LegacyPayment)
def test_discriminator_selects_model() -> None:
assert isinstance(PAYMENT.validate_python({"kind": "bank", "iban": "DE89370400440532013000"}), BankTransfer)
def test_discriminated_error_names_one_branch() -> None:
with pytest.raises(ValidationError) as exc:
PAYMENT.validate_python({"kind": "card", "brand": "amex", "last4": "12"})
locs = [e["loc"] for e in exc.value.errors()]
assert locs == [("card", "brand"), ("card", "last4")]
def test_unknown_tag() -> None:
with pytest.raises(ValidationError) as exc:
PAYMENT.validate_python({"kind": "crypto"})
err = exc.value.errors()[0]
assert err["type"] == "union_tag_invalid"
assert err["ctx"] == {"discriminator": "'kind'", "tag": "crypto", "expected_tags": "'card', 'bank', 'wallet'"}
def test_plain_union_reports_every_member() -> None:
with pytest.raises(ValidationError) as exc:
PLAIN.validate_python({"kind": "card", "brand": "amex", "last4": "12"})
locs = [".".join(map(str, e["loc"])) for e in exc.value.errors()]
assert locs == ["Card.brand", "Card.last4", "BankTransfer.kind", "BankTransfer.iban", "Wallet.kind", "Wallet.provider"]
def test_callable_discriminator_with_tags() -> None:
assert isinstance(LEGACY.validate_python({"last4": "4242", "brand": "visa"}), Card)
assert isinstance(LEGACY.validate_python({"iban": "DE89370400440532013000"}), BankTransfer)
with pytest.raises(ValidationError) as exc:
LEGACY.validate_python({"something": "else"})
assert exc.value.errors()[0]["type"] == "union_tag_not_found"
def test_json_schema_has_mapping() -> None:
schema = PAYMENT.json_schema()
assert schema["discriminator"]["propertyName"] == "kind"
assert schema["discriminator"]["mapping"]["card"] == "#/$defs/Card"Generic models and RootModel Important
In plain words: A generic model is a model with a type parameter, Page[T], that you fill in where it is used: Page[OrderOut], Page[int]. A RootModel is a model whose whole value is one thing (a list, a dict, a string) rather than named fields.
Common misunderstanding: "Page[int] is only a hint." For Pydantic it is a real, separately validated class named Page[int]: Page[int].model_validate({"items": ["1", 2], ...}).items == [1, 2] and ["x"] fails (asserted). The migration guide warns that isinstance(m, MyGenericModel[int]) should not be used; isinstance(m, MyGenericModel) is fine. v1's GenericModel "is no longer necessary, and has been removed", and v1's __root__ field was replaced by RootModel.
Definition: class Page(BaseModel, Generic[T]) (3.12+: class Page[T](BaseModel)); class Tags(RootModel[list[str]]) with the value in .root; validators on a root model target the field name "root".
1 Page[int].model_validate({"items": ["1", 2], "total": 2}) -> items=[1, 2]
2 .model_dump() -> {"items": [1, 2], "total": 2, "next_cursor": None, "count": 2}
3 Tags.model_validate([" Sale", "sale", "", "New"]).root -> ["new", "sale"]
4 Tags(...).model_dump_json() -> '["new","sale"]' (no {"root": ...} wrapper)Real scenario: paginated responses (Page[OrderOut]), a Result[T] envelope with data and errors, a top-level JSON array body (RootModel[list[OrderLine]]), a map of SKU to quantity (RootModel[dict[str, int]]).
| Need | Use |
|---|---|
| Envelope reused for many item types | class Page(BaseModel, Generic[T]) |
| Top-level JSON array or scalar | RootModel[list[X]] or a TypeAdapter |
| Normalise a list as a whole | @field_validator("root") on a RootModel |
isinstance on a parametrised model | Subclass it: class OrderPage(Page[OrderOut]) |
Fix / how to use it: a generic Page[T] per API (FastAPI documents each parametrisation separately in OpenAPI), RootModel only when the body is genuinely not an object; otherwise a TypeAdapter.
TypeAdapter and validate_call Important
In plain words: TypeAdapter(T) gives any type (a list[Model], a TypedDict, a union, dict[str, int]) the methods a model has: validate_python, validate_json, dump_python, dump_json, json_schema. @validate_call validates a function's arguments (and optionally its return value) from its annotations.
Common misunderstanding: "Creating a TypeAdapter is cheap." It builds a validator and serialiser each time: "Each time a TypeAdapter is instantiated, it will construct a new validator and serializer. If you’re using a TypeAdapter in a function, it will be instantiated each time the function is called. Instead, instantiate it once, and reuse it." Measured: 13.2 µs per call reused, 65.6 µs rebuilt per call (real run). Second: "validate_return=True rejects a wrong return type." In lax mode it converts: lax_total returns the string "3" and the caller gets the int 3; only config=ConfigDict(strict=True) turns it into an int_type error (both asserted).
Definition: "Pydantic provides TypeAdapter, which can be used for type validation, serialization, and JSON schema generation without needing to create a BaseModel." It replaces v1's parse_obj_as and schema_of. validate_call(func=None, *, config=None, validate_return=False).
"""TypeAdapter and validate_call: Pydantic for types that are not BaseModel subclasses.
Build adapters ONCE at module level: constructing one compiles a validator and a
serializer (the expensive part); calling it is cheap.
"""
from __future__ import annotations
from typing import Annotated, Dict, List, Optional, Union
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, validate_call
from typing_extensions import TypedDict
from app.models import BankTransfer, Card, OrderLine, Payment, Wallet
class StockRow(TypedDict): # typing_extensions.TypedDict: Pydantic requires it on < 3.12
sku: str
on_hand: int
LINES = TypeAdapter(List[OrderLine])
PAYMENT: TypeAdapter[Union[Card, BankTransfer, Wallet]] = TypeAdapter(Payment) # an Annotated union has no class to call
STOCK = TypeAdapter(List[StockRow])
SKU_COUNTS = TypeAdapter(Dict[str, Annotated[int, Field(ge=0)]])
MAYBE_INT: TypeAdapter[Optional[int]] = TypeAdapter(Optional[int]) # on 3.9 `int | None` here raises TypeError at import
@validate_call
def reserve(sku: Annotated[str, Field(min_length=3)], qty: Annotated[int, Field(gt=0)] = 1) -> str:
# Arguments are validated (and coerced in lax mode) on every call.
return f"{sku}x{qty}"
@validate_call(validate_return=True)
def lax_total(prices: List[int]) -> int:
return str(sum(prices)) # type: ignore[return-value] # lax mode: "3" is coerced back to 3
@validate_call(validate_return=True, config=ConfigDict(strict=True))
def strict_total(prices: List[int]) -> int:
return str(sum(prices)) # type: ignore[return-value] # strict: the str return is an error
class HeavyReport(BaseModel):
"""defer_build: the validator is built on first use instead of at import time."""
model_config = ConfigDict(defer_build=True)
rows: List[StockRow]
lines: List[OrderLine]1 LINES = TypeAdapter(List[OrderLine]) # module level: built once at import
2 LINES.validate_python([...]) # 13 us for 10 lines
3 TypeAdapter(List[OrderLine]).validate_python() # 66 us: schema built every call
4 reserve("ABC", "2") -> "ABCx2" ("2" coerced); reserve("AB", 0) -> string_too_short, greater_than
5 strict_total([1, 2]) -> ValidationError int_type on the return valueReal scenario: validating a JSON array of order lines from a CSV import; a dict[str, Annotated[int, Field(ge=0)]] stock map from Redis; service-layer functions called from Celery tasks or CLI commands (no FastAPI in front) wrapped in @validate_call; generating a JSON Schema for a non-model type used in an event catalogue.
| Need | Tool |
|---|---|
| Validate a list of models in one call | TypeAdapter(list[Model]).validate_json(body) |
Validate a TypedDict / dataclass / union | TypeAdapter(T) |
| JSON Schema of any type | TypeAdapter(T).json_schema() |
| Validate function arguments | @validate_call |
| Also validate the return value | @validate_call(validate_return=True) (+ strict to reject) |
Fix / how to use it: module-level adapters, imported where used; @validate_call at service boundaries that are not behind FastAPI; never construct an adapter inside a hot function.
"""TypeAdapter, validate_call, generics, RootModel, defer_build."""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from app.adapters import LINES, MAYBE_INT, SKU_COUNTS, STOCK, HeavyReport, lax_total, reserve, strict_total
from app.models import Page, Tags
def test_type_adapter_validates_lists_and_typeddicts() -> None:
rows = STOCK.validate_json('[{"sku": "ABC-1234", "on_hand": "7"}]')
assert rows == [{"sku": "ABC-1234", "on_hand": 7}] and type(rows[0]) is dict
assert SKU_COUNTS.validate_python({"ABC-1234": "3"}) == {"ABC-1234": 3}
assert MAYBE_INT.validate_python(None) is None
with pytest.raises(ValidationError):
SKU_COUNTS.validate_python({"ABC-1234": -1})
def test_type_adapter_dumps_and_schema() -> None:
lines = LINES.validate_python([{"sku": "abc-1234", "qty": 1, "unitPrice": {"amount": "2.5"}}])
assert LINES.dump_json(lines, by_alias=True).startswith(b'[{"sku":"ABC-1234","qty":1,"unitPrice"')
assert LINES.json_schema()["type"] == "array"
def test_validate_call_coerces_and_rejects() -> None:
assert reserve("ABC", "2") == "ABCx2" # type: ignore[arg-type]
with pytest.raises(ValidationError) as exc:
reserve("AB", 0)
assert [e["type"] for e in exc.value.errors()] == ["string_too_short", "greater_than"]
def test_validate_call_return() -> None:
assert lax_total([1, 2]) == 3 and type(lax_total([1, 2])) is int # coerced, not rejected
with pytest.raises(ValidationError) as exc:
strict_total([1, 2])
assert exc.value.errors()[0]["type"] == "int_type"
def test_generic_model() -> None:
page = Page[int].model_validate({"items": ["1", 2], "total": 2})
assert page.items == [1, 2]
assert page.model_dump() == {"items": [1, 2], "total": 2, "next_cursor": None, "count": 2}
assert Page[int].__name__ == "Page[int]"
with pytest.raises(ValidationError):
Page[int].model_validate({"items": ["x"], "total": 1})
def test_root_model() -> None:
tags = Tags.model_validate([" Sale", "sale", "", "New"])
assert tags.root == ["new", "sale"]
assert tags.model_dump_json() == '["new","sale"]'
def test_defer_build() -> None:
assert HeavyReport.__pydantic_complete__ is False # nothing built at import time
report = HeavyReport.model_validate({"rows": [], "lines": []})
assert report.rows == [] and HeavyReport.__pydantic_complete__ is Truemodel_config and ConfigDict: extra, frozen, populate_by_name, from_attributes Must-know
In plain words: model_config = ConfigDict(...) sets behaviour for one model: what to do with unknown keys, whether instances can change, how aliases work, whether objects can be read by attribute, strictness, string stripping and more.
Common misunderstanding: "Unknown keys are rejected by default." For BaseModel the default for extra forbid ignore allow is "ignore": an isAdmin key is dropped silently (and the nested OrderLine ignores colour, asserted). That is safe against mass assignment but hides client typos; extra="forbid" turns them into extra_forbidden errors. BaseSettings defaults to extra="forbid" (real run: an unknown APP_TYPO in .env → extra_forbidden). Second: "config is inherited only if I repeat it." Subclasses merge the parent's config (OrderIn.model_config shows alias_generator from CamelModel plus its own extra, real run); nested field models are separate classes with their own config.
Definition: keys used on this page: extra ("Whether to ignore, allow, or forbid extra data during model initialization. Defaults to 'ignore'."), frozen ("Whether models are faux-immutable, i.e. whether setattr is allowed, and also generates a hash() method for the model"), from_attributes ("Whether to build models and look up discriminators of tagged unions using python object attributes"), populate_by_name/validate_by_name/validate_by_alias, serialize_by_alias, alias_generator, strict, validate_assignment, validate_default, str_strip_whitespace, coerce_numbers_to_str, hide_input_in_errors, regex_engine, defer_build, arbitrary_types_allowed, use_enum_values, revalidate_instances, ser_json_timedelta. v1's inner class Config still works with a PydanticDeprecatedSince20 warning; mixing it with model_config is a PydanticUserError (asserted).
OrderOut(from_attributes=True).model_validate(order) where order is the domain dataclass (real run)
1 reads order.id, order.status, order.customer_email, order.total (a property), order.placed_at
2 -> {"id": 41, "status": "paid", "customerEmail": "ana@example.com",
"total": {"amount": "28.00", "currency": "EUR"}, "placedAt": "2026-11-29T06:30:00Z", "isPaid": true}
3 same call with from_attributes=False -> model_type error ("Input should be a valid dictionary or instance of OrderOut")Real scenario: extra="forbid" on every input DTO of a public API so that {"role": "admin"} is rejected loudly; frozen=True on value objects used as dict keys or in sets (hash(Money(...)) works because Decimal and str are hashable, asserted; the docs: "potentially hashable if all the attributes are hashable", and a frozen model with a dict field raises TypeError: unhashable type: 'dict' and lets the dict be mutated, real run runs/p10_fix1-output.txt); from_attributes=True on output DTOs built from SQLAlchemy or SQLModel rows; hide_input_in_errors=True on models that receive card numbers or passwords so logs do not contain them (real run: the error line ends with [type=int_parsing] and no input).
| Key | Values | When |
|---|---|---|
extra | "ignore" / "forbid" / "allow" | forbid for input DTOs, allow for pass-through proxies |
frozen | bool | Value objects, cache keys |
from_attributes | bool | Output DTOs from ORM/domain objects (v1 orm_mode) |
validate_by_name (2.11+) / populate_by_name | bool | Accept Python names besides aliases |
serialize_by_alias (2.11+) | bool | Dump by alias by default |
strict | bool | Internal contracts |
validate_assignment | bool | Mutable models |
hide_input_in_errors | bool | Hides input in the printed error only; errors()/json() still contain input |
str_strip_whitespace | bool | Form input |
use_enum_values | bool | Store .value instead of the member |
arbitrary_types_allowed | bool | Fields of classes Pydantic does not know (checked with isinstance only) |
regex_engine | "rust-regex" / "python-re" | Look-arounds needed |
defer_build | bool | Many models, few used per process |
Fix / how to use it: define two or three base classes for the whole codebase (input base with extra="forbid", output base with from_attributes, value-object base with frozen) and derive everything from them.
JSON Schema: model_json_schema Important
In plain words: Every model can describe itself as a JSON Schema document: types, required fields, constraints, aliases, enums, unions with their discriminator. FastAPI puts these schemas into the OpenAPI document behind /docs.
Common misunderstanding: "One schema per model." There are two: mode="validation" (what the model accepts) and mode="serialization" (what it produces). Computed fields appear only in the serialization schema, marked readOnly and listed as required there (OrderLine serialization required is sku, qty, unitPrice, lineTotal, validation required is sku, qty, unitPrice; real run). Fields with defaults stay optional in both unless json_schema_serialization_defaults_required=True.
Definition: BaseModel.model_json_schema(by_alias=True, ref_template=..., schema_generator=GenerateJsonSchema, mode="validation"); TypeAdapter(T).json_schema(); Field(title=, description=, examples=, json_schema_extra=); ConfigDict(json_schema_extra=...). Pydantic emits JSON Schema Draft 2020-12 with OpenAPI-compatible extensions such as discriminator.
OrderIn.model_json_schema() (real run, excerpt)
1 "customerEmail": {"maxLength": 254, "pattern": "^[^@\\s]+@...", "type": "string"}
2 "lines": {"items": {"$ref": "#/$defs/OrderLine"}, "maxItems": 50, "minItems": 1, "type": "array"}
3 "payment": {"oneOf": [Card, BankTransfer, Wallet refs], "discriminator": {"propertyName": "kind", "mapping": {...}}}
4 "placedAt": {"format": "date-time", "type": "string"}
5 "required": ["customerEmail", "lines", "payment", "placedAt"], "additionalProperties": falseReal scenario: OpenAPI for a FastAPI service and the TypeScript client generated from it; JSON Schema for event payloads in a schema registry; form generation in an admin UI; validating LLM structured output against the same schema the model was prompted with.
| Model feature | JSON Schema |
|---|---|
extra="forbid" | "additionalProperties": false |
Field(gt=0) | "exclusiveMinimum": 0 |
Field(min_length=1) on a list | "minItems": 1 |
pattern= | "pattern" |
Literal[...] / Enum | "enum" / "const" |
| Discriminated union | "oneOf" + "discriminator" |
alias_generator | Property names are the aliases (default by_alias=True) |
computed_field | Serialization mode only, "readOnly": true |
Custom type with GetPydanticSchema | From the JSON-side core schema ({"type": "string"} for Postcode) |
Fix / how to use it: add description and examples to public fields, check the generated schema in a test (tests/test_json_schema.py), and diff /openapi.json in CI.
"""model_json_schema(): validation vs serialization mode, aliases, constraints, $defs."""
from __future__ import annotations
from app.models import OrderIn, OrderLine
def test_input_schema_uses_aliases_and_constraints() -> None:
schema = OrderIn.model_json_schema()
props = schema["properties"]
assert "customerEmail" in props and "customer_email" not in props
assert props["lines"]["minItems"] == 1 and props["lines"]["maxItems"] == 50
assert schema["additionalProperties"] is False # extra="forbid"
assert set(schema["required"]) == {"customerEmail", "lines", "payment", "placedAt"}
assert "Card" in schema["$defs"] and schema["$defs"]["OrderLine"]["properties"]["qty"]["exclusiveMinimum"] == 0
def test_validation_alias_choices_document_first_choice() -> None:
assert "placedAt" in OrderIn.model_json_schema()["properties"]
def test_serialization_schema_includes_computed_fields() -> None:
validation = OrderLine.model_json_schema(mode="validation")["properties"]
serialization = OrderLine.model_json_schema(mode="serialization")["properties"]
assert "lineTotal" not in validation
assert serialization["lineTotal"]["readOnly"] is TrueCustom types and GetPydanticSchema Good to know
In plain words: When a field's type is a class Pydantic does not know (a Postcode from a library, your own Cents), you tell Pydantic how to validate and serialise it: for a class you own, a __get_pydantic_core_schema__ classmethod; for one you do not own, Annotated[Postcode, GetPydanticSchema(fn)].
Common misunderstanding: "arbitrary_types_allowed=True is the way to support custom types." It only allows isinstance checks: no parsing from strings, no JSON Schema, no serialisation. A core schema gives all three. Second: "to_string_ser_schema() makes model_dump() return strings." By default it applies in JSON mode only (model_dump() keeps the Postcode object, model_dump_json() writes "12345-67890", asserted).
Definition: a core schema is built from pydantic_core.core_schema helpers (str_schema, int_schema, no_info_after_validator_function, no_info_before_validator_function, no_info_plain_validator_function, json_or_python_schema, to_string_ser_schema …). The docs: "For many simple cases you can greatly minimize this by using pydantic.GetPydanticSchema". Errors raised as PydanticCustomError("postcode", "postcode must be 10 digits, got {raw}", {"raw": raw}) keep your own error type.
"""Custom types: teach Pydantic a class it does not know.
Two routes: a class you own implements __get_pydantic_core_schema__; a class you
do not own (a third-party type) is wrapped with Annotated[..., GetPydanticSchema(...)].
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Annotated, Any
from pydantic import BaseModel, GetCoreSchemaHandler, GetPydanticSchema
from pydantic_core import PydanticCustomError, core_schema
class Postcode:
"""Pretend this class comes from a library you cannot edit: 10 digits, no dash."""
def __init__(self, raw: str) -> None:
digits = raw.replace("-", "")
if len(digits) != 10 or not digits.isdigit():
raise PydanticCustomError("postcode", "postcode must be 10 digits, got {raw}", {"raw": raw})
self.digits = digits
def __str__(self) -> str:
return f"{self.digits[:5]}-{self.digits[5:]}"
def __eq__(self, other: object) -> bool:
return isinstance(other, Postcode) and other.digits == self.digits
def _to_postcode(value: Any) -> Postcode:
if isinstance(value, Postcode):
return value
if not isinstance(value, str): # 123, None, ... -> a ValidationError, not an AttributeError
raise PydanticCustomError("string_type", "Input should be a valid string")
return Postcode(value.strip())
def _postcode_schema(source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
return core_schema.json_or_python_schema(
# JSON input: a string, stripped, then turned into a Postcode
json_schema=core_schema.no_info_after_validator_function(Postcode, core_schema.str_schema(strip_whitespace=True)),
# Python input: a Postcode instance, or a string (anything else is a string_type error)
python_schema=core_schema.no_info_plain_validator_function(_to_postcode),
serialization=core_schema.to_string_ser_schema(), # dump as str(postcode), JSON mode only
)
PostcodeField = Annotated[Postcode, GetPydanticSchema(_postcode_schema)]
class Cents(int):
"""A class we own: integer cents that also accept "12.50" strings.
Strings are parsed with Decimal: the sign is kept (so ge=0 can reject "-0.50") and more
than two fractional digits is an error, never a silent truncation.
"""
@classmethod
def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
def parse(value: Any) -> Any:
if isinstance(value, str) and "." in value:
try:
amount = Decimal(value.strip())
except InvalidOperation:
raise PydanticCustomError("cents_parsing", "not a decimal amount: {raw}", {"raw": value})
if amount.as_tuple().exponent < -2: # type: ignore[operator]
raise PydanticCustomError("cents_precision", "at most 2 decimal places, got {raw}", {"raw": value})
return int(amount * 100) # exact: at most 2 places
return value # ints and int-like strings: int_schema decides (floats with a fraction fail)
return core_schema.no_info_after_validator_function(
cls, core_schema.no_info_before_validator_function(parse, core_schema.int_schema(ge=0))
)
class Address(BaseModel):
street: str
postcode: PostcodeField
shipping_fee: Cents = Cents(0)1 Address.model_validate({"street": "Main 1", "postcode": " 1234567890 "})
2 python_schema: strip -> _to_postcode -> Postcode("1234567890")
3 model_dump_json() -> {"street":"Main 1","postcode":"12345-67890","shipping_fee":0}
4 postcode "12-34" -> {"type": "postcode", "loc": ("postcode",), "msg": "postcode must be 10 digits, got 12-34"}
5 shipping_fee "12.5" -> Decimal -> 1250; "-0.50" -> -50 -> greater_than_equal; "1.999" -> cents_precision (never truncated)Real scenario: postcodes, IBANs, phone numbers backed by a parsing library; money types from a money library; ObjectId from MongoDB drivers; domain value objects that must round-trip through JSON.
| Situation | Approach |
|---|---|
| A rule on an existing type | Annotated[str, AfterValidator(...)] (no core schema needed) |
| A class you own | __get_pydantic_core_schema__ (+ __get_pydantic_json_schema__ if needed) |
| A class you do not own | Annotated[Cls, GetPydanticSchema(fn)] |
Only isinstance needed | arbitrary_types_allowed=True |
Fix / how to use it: start with Annotated validators; write a core schema only when the type needs its own parsing and serialisation, and test its JSON Schema.
"""GetPydanticSchema for a foreign class; __get_pydantic_core_schema__ for our own."""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from app.custom_types import Address, Postcode
def test_foreign_class_via_get_pydantic_schema() -> None:
addr = Address.model_validate({"street": "Main 1", "postcode": " 1234567890 "})
assert isinstance(addr.postcode, Postcode) and str(addr.postcode) == "12345-67890"
assert addr.model_dump_json() == '{"street":"Main 1","postcode":"12345-67890","shipping_fee":0}'
assert isinstance(addr.model_dump()["postcode"], Postcode) # to_string_ser_schema: JSON mode only
def test_custom_error_type() -> None:
with pytest.raises(ValidationError) as exc:
Address.model_validate({"street": "x", "postcode": "12-34"})
err = exc.value.errors()[0]
assert (err["type"], err["msg"], err["loc"]) == ("postcode", "postcode must be 10 digits, got 12-34", ("postcode",))
def test_own_class_with_core_schema_hook() -> None:
assert Address(street="x", postcode="1234567890", shipping_fee="12.5").shipping_fee == 1250 # type: ignore[arg-type]
with pytest.raises(ValidationError):
Address(street="x", postcode="1234567890", shipping_fee=-1) # type: ignore[arg-type]
def test_custom_type_in_json_schema() -> None:
props = Address.model_json_schema()["properties"]
assert props["postcode"] == {"title": "Postcode", "type": "string"}
assert props["shipping_fee"]["minimum"] == 0
def test_non_string_postcode_is_a_validation_error() -> None:
with pytest.raises(ValidationError) as exc:
Address.model_validate({"street": "x", "postcode": 123})
assert [(e["type"], e["loc"]) for e in exc.value.errors()] == [("string_type", ("postcode",))]
@pytest.mark.parametrize(
("fee", "expected"),
[("12.5", 1250), ("0.05", 5), (" 3.00 ", 300), (7, 7), ("-0.50", "greater_than_equal"),
("1.999", "cents_precision"), ("1.x", "cents_parsing"), (1.9, "int_from_float")],
)
def test_cents_keeps_sign_and_precision(fee: object, expected: object) -> None:
if isinstance(expected, int):
assert Address(street="x", postcode="1234567890", shipping_fee=fee).shipping_fee == expected # type: ignore[arg-type]
else:
with pytest.raises(ValidationError) as exc:
Address(street="x", postcode="1234567890", shipping_fee=fee) # type: ignore[arg-type]
assert exc.value.errors()[0]["type"] == expectedValidationError: errors(), loc, type, msg, input Must-know
In plain words: When validation fails, you get one ValidationError that lists every problem. Each problem is a small dict with loc type msg input (and often ctx and url): where it happened, a stable machine code, a human sentence, and the offending value.
Common misunderstanding: "Parse the msg text to decide what to do." Messages are for humans and may change; type is the stable identifier ("A computer-readable identifier of the error type"), and the error types are listed in the docs' error reference. Second: "loc uses Python field names." It uses the names as they appeared in the input, so aliases (customerEmail, isAdmin), list indexes (("lines", 0, "qty")) and union tags (("card", "last4")) show up there.
Definition: ValidationError.errors(include_url=True, include_context=True, include_input=True) returns a list of dicts; error_count(), title (the model name), json(); str(err) is the multi-line report. The docs: "The first item in the loc list will be the field where the error occurred, and if the field is a sub-model, subsequent items will be present to indicate the nested location of the error."
str(ValidationError) for a payload with five problems (real run, Pydantic 2.13.5)
1 5 validation errors for OrderIn
2 customerEmail
3 String should match pattern '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$' [type=string_pattern_mismatch, input_value='x', input_type=str]
4 For further information visit https://errors.pydantic.dev/2.13/v/string_pattern_mismatch
5 lines
6 List should have at least 1 item after validation, not 0 [type=too_short, input_value=[], input_type=list]
7 payment
8 Input tag 'cash' found using 'kind' does not match any of the expected tags: 'card', 'bank', 'wallet' [type=union_tag_invalid, ...]
9 placedAt
10 Input should be a valid datetime or date, input is too short [type=datetime_from_date_parsing, input_value='yesterday', input_type=str]
11 isAdmin
12 Extra inputs are not permitted [type=extra_forbidden, input_value=True, input_type=bool]Real scenario: FastAPI wraps these into a 422 response body ({"detail": [...]} with the same type, loc, msg, input); a message consumer sends invalid events to a dead-letter queue with err.json() attached; a CSV import reports "row 12, column qty: Input should be greater than 0" by mapping loc; a frontend maps type codes to translated messages.
| Error type (real) | Meaning |
|---|---|
missing | Required field absent |
extra_forbidden | Unknown key with extra="forbid" |
int_parsing / int_from_float / int_type | Not an int / float with fraction / strict |
bool_parsing / bool_type | Not a recognised bool / strict |
string_type / string_too_short / string_too_long / string_pattern_mismatch | String rules |
too_short / too_long | List/set/dict length |
greater_than / less_than_equal / multiple_of | Numeric bounds |
decimal_max_places / decimal_max_digits | Decimal precision |
literal_error / enum | Value not allowed |
union_tag_invalid / union_tag_not_found | Discriminated union |
model_type | Object given where a dict or instance was expected |
datetime_parsing / datetime_from_date_parsing / timezone_aware | Date/time rules |
json_invalid | Malformed JSON in model_validate_json |
frozen_instance / frozen_field | Assignment to frozen model/field |
value_error / assertion_error | Raised in your validator |
custom (e.g. postcode) | PydanticCustomError |
Fix / how to use it: branch on type, show msg to developers, map loc to field paths for users, and never log input for sensitive models. hide_input_in_errors=True only changes the printed text ("Whether to hide inputs when printing errors"); the structured list still carries it (real run: errors()[0]["input"] == "4111-1111"). Strip it where you log or return errors: exc.errors(include_input=False, include_url=False) or exc.json(include_input=False), e.g. in an exception handler that builds the 422 body from that list.
Performance and defer_build Important
In plain words: Validation itself is fast (microseconds per object, in Rust). What makes Pydantic code slow is avoidable: building validators repeatedly, round-tripping JSON through Python dicts, wrap validators and Python callbacks on every item, plain unions with many members, and models built at import time that a process never uses.
Common misunderstanding: "defer_build=True makes validation faster." It moves the schema build from import time to the first validation; it helps start-up time of processes that import many models and use few (CLIs, serverless functions, test collection). Measured here on small models: 177 µs vs 150 µs per class creation (real run), a small difference, because most of the cost appears at first use instead.
Definition: the docs' tips: "use model_validate_json() not model_validate(json.loads(...))", "TypeAdapter instantiated once", prefer list/dict over Sequence/Mapping ("When using Sequence, Pydantic calls isinstance(value, Sequence)"), "Use tagged union, not union", "Use TypedDict over nested models" (about 2.5x faster in their benchmark), "Avoid wrap validators if you really care about performance", FailFast for sequences (2.8+), and Any for values you do not need validated. defer_build: "Whether to defer model validator and serializer construction until the first model validation. Defaults to False."
tests/test_perf.py -s (real, CPython 3.9.6, Apple Silicon laptop, Pydantic 2.13.5)
1 TypeAdapter reused: 13.2 us/call (10 order lines)
2 TypeAdapter rebuilt per call: 65.6 us/call
3 OrderIn.model_validate_json: 6.3 us (2 lines, discriminated payment)
4 json.loads + model_validate: 6.8 us
5 model_validate(dict): 4.8 us
6 model_dump_json: 7.1 usReal scenario: (arithmetic from the measured numbers above) an API serving 2,000 requests per second spends about 10 ms of CPU per second on 5 µs validations: noise next to a database query; the same API building a TypeAdapter inside each handler spends about 130 ms per second; a serverless function importing 400 models gains start-up time with defer_build; a bulk import of a million rows uses TypeAdapter(list[RowDict]).validate_json once instead of a million model calls.
| Tip | Gain | Cost |
|---|---|---|
Reuse TypeAdapter / models | No rebuild per call (5x here) | None |
model_validate_json on bytes | No Python dict in between | None |
| Discriminated unions | One member validated | A tag field |
TypedDict for inner rows | Fewer objects | No methods |
| Avoid wrap/plain Python validators in hot loops | Stay in Rust | Express rules as constraints |
defer_build=True | Faster import | First use pays |
FailFast() on long lists | Stop at first bad item | Fewer errors reported |
Fix / how to use it: measure before tuning (the snippet's _per_call_us helper is enough); fix the structural issues above first, they matter more than micro-tuning.
"""Relative validation cost. Run with -s to see the numbers; only robust ratios are asserted."""
from __future__ import annotations
import json
import time
from typing import Any, Callable, List
from pydantic import TypeAdapter
from app.models import OrderIn, OrderLine
LINE = {"sku": "ABC-1234", "qty": 2, "unitPrice": {"amount": "12.50", "currency": "EUR"}}
REUSED = TypeAdapter(List[OrderLine])
def _per_call_us(fn: Callable[[], Any], n: int) -> float:
fn() # warm-up
start = time.perf_counter()
for _ in range(n):
fn()
return (time.perf_counter() - start) / n * 1e6
def test_reuse_type_adapter(order_payload: dict[str, Any]) -> None:
lines = [LINE] * 10
reused = _per_call_us(lambda: REUSED.validate_python(lines), 2000)
rebuilt = _per_call_us(lambda: TypeAdapter(List[OrderLine]).validate_python(lines), 200)
print(f"\nTypeAdapter reused: {reused:.1f} us/call; rebuilt every call: {rebuilt:.1f} us/call")
assert rebuilt > 2 * reused # schema build on every call
def test_validate_json_vs_loads_then_validate(order_payload: dict[str, Any]) -> None:
text = json.dumps(order_payload)
direct = _per_call_us(lambda: OrderIn.model_validate_json(text), 5000)
two_step = _per_call_us(lambda: OrderIn.model_validate(json.loads(text)), 5000)
dict_only = _per_call_us(lambda: OrderIn.model_validate(order_payload), 5000)
dump = _per_call_us(lambda: OrderIn.model_validate(order_payload).model_dump_json(), 5000) - dict_only
print(
f"\nmodel_validate_json: {direct:.1f} us; json.loads + model_validate: {two_step:.1f} us; "
f"model_validate(dict): {dict_only:.1f} us; model_dump_json: {dump:.1f} us"
)
assert direct < 1000 and two_step < 1000 # well under a millisecond per order either wayv1 to v2 migration: parse_obj deprecated, orm_mode renamed Important
In plain words: Pydantic v2 renamed most model methods with a model_ prefix, replaced @validator/@root_validator with @field_validator/@model_validator, class Config with model_config = ConfigDict(...), and changed several defaults (stricter number-to-string rules, Rust regexes). The old names mostly still run, with warnings.
Common misunderstanding: "If it runs without errors, the migration is done." The v1 methods run and emit PydanticDeprecatedSince20 warnings that you only see if warnings are shown (pytest shows them; production logs often do not), and behaviour changed underneath: str fields no longer accept numbers, allow_mutation and smart_union are simply "removed" (real warning text), regexes with look-arounds fail. The pydantic.v1 namespace still exists in 2.x for gradual moves (2.13's matches v1 1.10.26, per the release notes), and FastAPI dropped v1 support entirely in 0.126.0.
Definition: the migration guide provides bump-pydantic (pip install bump-pydantic) for automated rewrites. Real warning texts from 2.13.5: "Support for class-based config is deprecated, use ConfigDict instead. Deprecated in Pydantic V2.0 to be removed in V3.0." and "Valid config keys have changed in V2: * 'orm_mode' has been renamed to 'from_attributes'".
v1 code running on Pydantic 2.13.5 (real runs, tests/test_migration.py and runs/p4_v1_config-output.txt)
1 Money.parse_obj({...}) -> works + PydanticDeprecatedSince20 (use model_validate)
2 Money.parse_raw('{...}') -> works + warning (use model_validate_json)
3 m.dict() / m.json() / m.copy() -> work + warnings (model_dump / model_dump_json / model_copy)
4 class Config: orm_mode = True -> warning: renamed to 'from_attributes'
5 class Config: allow_population_by_field_name = True -> renamed to 'validate_by_name'
6 class Config: smart_union = True -> "has been removed"
7 @validator("name") -> PydanticDeprecatedSince20
8 model_config = {...} AND class Config -> PydanticUserErrorReal scenario: a FastAPI service pinned to pydantic<2 that must upgrade to get current FastAPI; a shared models package used by v1 and v2 services during the transition (pydantic.v1); a test suite run with -W error::DeprecationWarning to find every remaining v1 call.
| Pydantic v1 | Pydantic v2 |
|---|---|
Model.parse_obj(d) | Model.model_validate(d) |
Model.parse_raw(s) | Model.model_validate_json(s) |
Model.from_orm(o) + orm_mode | Model.model_validate(o) + from_attributes=True |
m.dict() / m.json() | m.model_dump() / m.model_dump_json() |
m.copy() | m.model_copy() |
Model.schema() | Model.model_json_schema() |
Model.construct() | Model.model_construct() |
Model.update_forward_refs() | Model.model_rebuild() |
__fields__ | model_fields |
@validator, @root_validator | @field_validator, @model_validator |
class Config: | model_config = ConfigDict(...) |
allow_population_by_field_name | validate_by_name (populate_by_name before 2.11) |
anystr_strip_whitespace | str_strip_whitespace |
GenericModel | BaseModel + Generic[T] |
__root__ | RootModel |
parse_obj_as, schema_of | TypeAdapter |
Field(regex=...), const= | Field(pattern=...); Literal |
BaseSettings in pydantic | pydantic-settings package |
Fix / how to use it: run bump-pydantic, then the test suite with deprecation warnings as errors, then review behaviour changes (number-to-string coercion, regexes, Optional without default now required).
"""v1 -> v2: old names still run but warn; some v1 config keys changed name."""
from __future__ import annotations
import warnings
from decimal import Decimal
import pytest
from pydantic import BaseModel, PydanticDeprecatedSince20
from pydantic.errors import PydanticUserError
from app.models import Money
@pytest.mark.parametrize(
("call", "replacement"),
[
(lambda: Money.parse_obj({"amount": "1"}), "model_validate"),
(lambda: Money.parse_raw('{"amount": "1"}'), "model_validate_json"),
(lambda: Money(amount=Decimal(1)).dict(), "model_dump"),
(lambda: Money(amount=Decimal(1)).json(), "model_dump_json"),
(lambda: Money.schema(), "model_json_schema"),
(lambda: Money(amount=Decimal(1)).copy(), "model_copy"),
],
)
def test_v1_methods_warn(call: object, replacement: str) -> None:
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
call() # type: ignore[operator]
messages = [str(w.message) for w in caught if issubclass(w.category, PydanticDeprecatedSince20)]
assert messages and replacement in messages[0]
def test_v1_config_key_renamed_warns() -> None:
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
class Row(BaseModel):
class Config:
orm_mode = True
id: int
text = " ".join(str(w.message) for w in caught)
assert "orm_mode" in text and "from_attributes" in text
def test_validator_decorator_v1_style_is_deprecated() -> None:
from pydantic import validator
with pytest.warns(PydanticDeprecatedSince20):
class Legacy(BaseModel):
name: str
@validator("name")
def strip(cls, v: str) -> str: # noqa: N805
return v.strip()
def test_mixing_config_class_and_model_config_is_an_error() -> None:
with pytest.raises(PydanticUserError, match="Config"):
class Both(BaseModel):
model_config = {"frozen": True}
class Config:
frozen = Truepydantic-settings: BaseSettings, env_prefix, env_nested_delimiter, secrets_dir, dotenv Must-know
In plain words: BaseSettings is a model whose values come from the environment: environment variables, a .env (dotenv) file and a secrets directory, in that order of priority, with defaults last. Because it is a Pydantic model, a missing or malformed setting fails at startup, with the field named.
Common misunderstanding: "Settings read the environment every time I access them." They read once, when you instantiate Settings(); that is why apps create it once (FastAPI apps usually cache it, see APIRouter & Project Structure). Second: "extra='forbid' catches typos in environment variable names." It catches unknown keys from sources that pass them in (dotenv), but the docs say "Environment variables that do not match a settings field or its alias are ignored, even if they start with env_prefix and extra='forbid' is set." A misspelled SHOP_DEBG simply leaves the default.
Definition: pip install pydantic-settings (a separate package since v2). The docs' priority list: "Arguments passed to the Settings class initialiser." > "Environment variables" > "Variables loaded from a dotenv (.env) file." > "Variables loaded from the secrets directory." > "The default field values for the Settings model." (with CLI arguments on top when cli_parse_args is on). "By default, environment variable names are case-insensitive." Complex types (lists, dicts, sub-models) are read as JSON strings, or field by field with env_nested_delimiter. SecretStr hides the value in repr and logs (SecretStr('**********')).
"""pydantic-settings: typed configuration from environment variables, .env files and a secrets dir.
How FastAPI wires this into an app (lifespan, Depends, lru_cache) is in the
APIRouter & Project Structure chapter; this file is the library itself.
"""
from __future__ import annotations
from pydantic import BaseModel, Field, PostgresDsn, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class DatabaseSettings(BaseModel):
url: PostgresDsn = PostgresDsn("postgresql://shop@localhost:5432/shop")
pool_size: int = Field(default=5, ge=1, le=100)
echo: bool = False
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="SHOP_", # SHOP_DEBUG -> debug
env_nested_delimiter="__", # SHOP_DB__POOL_SIZE -> db.pool_size
env_file=".env", # read if it exists; real environment variables win
env_file_encoding="utf-8",
secrets_dir=None, # set per deployment, e.g. "/run/secrets" (Docker/Kubernetes)
extra="ignore", # other SHOP_* keys in .env are ignored
)
app_name: str = "shop"
debug: bool = False
allowed_hosts: list[str] = ["localhost"] # complex types are read as JSON: '["a","b"]'
db: DatabaseSettings = DatabaseSettings()
payment_api_key: SecretStr # required: no default, startup fails without it precedence, real run (tests/test_settings.py)
1 no SHOP_PAYMENT_API_KEY anywhere -> ValidationError loc ("payment_api_key",) type missing: the app does not start
2 .env: SHOP_PAYMENT_API_KEY=from_dotenv -> "from_dotenv"
3 + env SHOP_PAYMENT_API_KEY=from_env -> "from_env" (environment beats .env)
4 + Settings(payment_api_key="from_init") -> "from_init" (init beats everything)
5 secrets dir file shop_payment_api_key -> "from_secret_file" (lowest file source)
6 SHOP_DB__POOL_SIZE=20 -> settings.db.pool_size == 20 (env_nested_delimiter="__")
7 SHOP_ALLOWED_HOSTS='["api.example.com","admin.example.com"]' -> list[str] parsed from JSONReal scenario: a twelve-factor service configured only by environment variables in Kubernetes; Docker or Kubernetes secrets mounted as files under /run/secrets read through secrets_dir; local development with a .env file that is git-ignored; nested database settings overridden per environment with SHOP_DB__POOL_SIZE; a CI job that fails at import because SHOP_PAYMENT_API_KEY is missing instead of at the first payment.
| Option | Example | Effect |
|---|---|---|
env_prefix | "SHOP_" | SHOP_DEBUG → debug |
env_nested_delimiter | "__" | SHOP_DB__POOL_SIZE → db.pool_size |
env_file | ".env" or a tuple of files | dotenv source; later files win |
env_file_encoding | "utf-8" | |
secrets_dir | "/run/secrets" | One file per field, file name = env name |
case_sensitive | False (default) | Names matched case-insensitively |
extra | "forbid" (default) | Unknown dotenv keys fail; set "ignore" for shared .env files |
SecretStr / SecretBytes | payment_api_key: SecretStr | Masked in repr; .get_secret_value() to read |
_env_file=, _secrets_dir= | Settings(_secrets_dir=path) | Per-instance overrides (used in tests) |
Fix / how to use it: one Settings class per service, instantiated once at startup, required secrets without defaults, SecretStr for every credential, extra="ignore" only when a shared .env holds other services' keys, and tests that set environment variables with monkeypatch.
"""pydantic-settings: precedence init > env > .env > secrets dir > defaults."""
from __future__ import annotations
from pathlib import Path
import pytest
from pydantic import ValidationError
from app.settings import Settings
@pytest.fixture(autouse=True)
def clean_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.chdir(tmp_path) # no stray .env from the working directory
for key in ("SHOP_DEBUG", "SHOP_DB__POOL_SIZE", "SHOP_PAYMENT_API_KEY", "SHOP_ALLOWED_HOSTS"):
monkeypatch.delenv(key, raising=False)
def test_required_secret_missing_fails_at_startup() -> None:
with pytest.raises(ValidationError) as exc:
Settings() # type: ignore[call-arg]
assert exc.value.errors()[0]["loc"] == ("payment_api_key",)
assert exc.value.errors()[0]["type"] == "missing"
def test_env_prefix_nested_delimiter_and_json(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("SHOP_PAYMENT_API_KEY", "sk_test_123")
monkeypatch.setenv("SHOP_DEBUG", "true")
monkeypatch.setenv("SHOP_DB__POOL_SIZE", "20")
monkeypatch.setenv("SHOP_ALLOWED_HOSTS", '["api.example.com", "admin.example.com"]')
s = Settings() # type: ignore[call-arg]
assert s.debug is True and s.db.pool_size == 20
assert s.allowed_hosts == ["api.example.com", "admin.example.com"]
assert str(s.db.url) == "postgresql://shop@localhost:5432/shop"
assert repr(s.payment_api_key) == "SecretStr('**********')"
assert s.payment_api_key.get_secret_value() == "sk_test_123"
def test_dotenv_and_env_precedence(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
(tmp_path / ".env").write_text("SHOP_PAYMENT_API_KEY=from_dotenv\nSHOP_DEBUG=true\nSHOP_UNRELATED=1\n")
assert Settings().payment_api_key.get_secret_value() == "from_dotenv" # type: ignore[call-arg]
monkeypatch.setenv("SHOP_PAYMENT_API_KEY", "from_env")
assert Settings().payment_api_key.get_secret_value() == "from_env" # type: ignore[call-arg]
assert Settings(payment_api_key="from_init").payment_api_key.get_secret_value() == "from_init"
def test_secrets_dir(tmp_path: Path) -> None:
secrets = tmp_path / "secrets"
secrets.mkdir()
(secrets / "shop_payment_api_key").write_text("from_secret_file") # file name = env name
s = Settings(_secrets_dir=secrets) # type: ignore[call-arg]
assert s.payment_api_key.get_secret_value() == "from_secret_file"
def test_bad_value_names_the_field(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("SHOP_PAYMENT_API_KEY", "k")
monkeypatch.setenv("SHOP_DB__POOL_SIZE", "0")
with pytest.raises(ValidationError) as exc:
Settings() # type: ignore[call-arg]
assert exc.value.errors()[0]["loc"] == ("db", "pool_size")DTO vs domain object: where Pydantic belongs Important
In plain words: A DTO (data transfer object) describes data crossing a boundary: a request body, a response, a message, a settings file. A domain object holds the business rules: an Order that can be paid once, whose total is computed, which emits an OrderPaid event. Pydantic is excellent at the first job; the second job does not need it.
Common misunderstanding: "Using Pydantic models everywhere keeps things consistent." It couples the domain to the wire format: renaming a JSON key becomes a domain change, validation runs again on every internal copy, and extra/alias settings leak into business code. The opposite mistake, "never use Pydantic inside", is also wrong for anaemic CRUD services where the DTO is the model; choose per service.
Definition: the snippet uses OrderIn (input DTO, extra="forbid", aliases, validators) → Order (a @dataclass with pay() and total, no aliases) → OrderOut (output DTO, from_attributes=True, computed_field, UTC serialiser). The JSON column path stores the DTO as JSON (model_dump_json(by_alias=True)) and reads it back with model_validate_json.
1 POST body (camelCase JSON) -> OrderIn.model_validate_json (edge: all validation here)
2 Order.from_dto(41, dto) -> domain object, plain dataclass
3 order.pay() -> status "paid", events ["OrderPaid"]; second pay() -> InvalidTransition
4 OrderOut.model_validate(order) -> reads attributes and the total property
5 out.model_dump(by_alias=True) -> {"id": 41, "status": "paid", ..., "placedAt": "2026-11-29T06:30:00Z", "isPaid": true}Real scenario: an order service with state transitions (domain object) behind a REST API (DTOs); a reporting service that only reads and reshapes data (DTOs only, no domain layer needed); SQLModel, which deliberately merges the table model and the Pydantic model and is convenient for CRUD, and needs separate OrderCreate/OrderRead models as soon as input and output differ (SQLAlchemy 2 & SQLModel).
| Input DTO | Domain object | Output DTO | Table model | |
|---|---|---|---|---|
| Library | Pydantic | dataclass / attrs / plain class | Pydantic | SQLAlchemy 2 / SQLModel |
| Knows aliases, JSON | Yes | No | Yes | No (columns) |
| Validates | Untrusted input | Invariants in methods | Output shape | Database constraints |
| Has behaviour | No | Yes | Computed fields only | Relationships |
| Changes when | API changes | Business rules change | API changes | Schema migrates (Alembic) |
Fix / how to use it: DTOs at every boundary, a domain layer where there are real rules, conversion functions (from_dto, model_validate(obj) with from_attributes) in between, and tests on each conversion.
"""A model stored in a JSON column (sqlite3 from the stdlib) and read back through Pydantic.
The same idea with PostgreSQL is a JSONB column; with SQLAlchemy 2 / SQLModel the
column type is JSON/JSONB and the DTO is validated on the way in and out.
"""
from __future__ import annotations
import sqlite3
from app.models import OrderIn
SCHEMA = """
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
payload TEXT NOT NULL CHECK (json_valid(payload)),
placed_at TEXT NOT NULL
)
"""
class OrderStore:
def __init__(self) -> None:
self.db = sqlite3.connect(":memory:")
self.db.execute(SCHEMA)
def add(self, dto: OrderIn) -> int:
cur = self.db.execute(
"INSERT INTO orders (email, payload, placed_at) VALUES (?, ?, ?)",
(dto.customer_email, dto.model_dump_json(by_alias=True), dto.placed_at.isoformat()),
)
return int(cur.lastrowid or 0)
def get(self, order_id: int) -> OrderIn:
(payload,) = self.db.execute("SELECT payload FROM orders WHERE id = ?", (order_id,)).fetchone()
return OrderIn.model_validate_json(payload) # JSON text -> model, parsed in Rust
def payment_kinds(self) -> list[tuple[str, int]]:
sql = (
"SELECT json_extract(payload, '$.payment.kind') AS kind, COUNT(*) "
"FROM orders GROUP BY kind ORDER BY kind"
)
return [(str(kind), int(n)) for kind, n in self.db.execute(sql)]"""DTO -> JSON column -> DTO, and DTO -> domain object -> output DTO (from_attributes)."""
from __future__ import annotations
from typing import Any
import pytest
from app.domain import InvalidTransition, Order
from app.models import OrderIn, OrderOut
from app.storage import OrderStore
def test_json_column_round_trip(order_payload: dict[str, Any]) -> None:
store = OrderStore()
dto = OrderIn.model_validate(order_payload)
oid = store.add(dto)
assert store.get(oid) == dto
order_payload["payment"] = {"kind": "wallet", "provider": "PayPal"}
store.add(OrderIn.model_validate(order_payload))
assert store.payment_kinds() == [("card", 1), ("wallet", 1)]
def test_domain_object_and_output_dto(order_payload: dict[str, Any]) -> None:
order = Order.from_dto(41, OrderIn.model_validate(order_payload))
order.pay()
with pytest.raises(InvalidTransition):
order.pay()
out = OrderOut.model_validate(order) # from_attributes reads attributes and properties
assert out.model_dump(by_alias=True) == {
"id": 41,
"status": "paid",
"customerEmail": "ana@example.com",
"total": {"amount": "28.00", "currency": "EUR"},
"placedAt": "2026-11-29T06:30:00Z",
"isPaid": True,
}
def test_without_from_attributes_objects_are_rejected(order_payload: dict[str, Any]) -> None:
from pydantic import ValidationError
order = Order.from_dto(1, OrderIn.model_validate(order_payload))
with pytest.raises(ValidationError) as exc:
OrderOut.model_validate(order, from_attributes=False)
assert exc.value.errors()[0]["type"] == "model_type"Mechanics
What happens inside one model_validate call Important
The validation pipeline diagram shows where each hook runs; this is the full path of one call in the snippet, with the component that does each step.
OrderIn.model_validate_json(body) (Pydantic 2.13.5, pydantic-core 2.46.5, CPython 3.9.6)
1 Python classmethod -> cls.__pydantic_validator__.validate_json(body) (built at class creation)
2 Rust jiter parses the bytes (json_invalid on malformed input)
3 Python cb model_validator(mode="before") _accept_legacy_items(data)
4 Rust model-fields validator: for each field, look up the key by alias / name (AliasChoices in order)
5 Rust extra="forbid": unknown keys -> extra_forbidden (collected, not raised yet)
6 Rust/Py per field: before validators (Python) -> core type + coercion + constraints (Rust) -> after validators (Python)
7 Rust nested OrderLine models and the discriminated Payment validated the same way (tag lookup first)
8 Rust any errors? -> raise ValidationError(title="OrderIn", line_errors=[...]) and stop
9 Rust build the instance: __dict__, __pydantic_fields_set__ (for exclude_unset), __pydantic_extra__
10 Python cb model_validator(mode="after") _one_currency(self) -> return self
11 Python instance returned; the request handler now holds typed dataHow a model class is built (and why the future import matters) Good to know
At class OrderIn(...) Pydantic's metaclass collects the annotations, resolves them to real types using the module's globals and the defining frame's locals (strings from from __future__ import annotations are evaluated here, which on 3.9 needs eval-type-backport for X | None), merges model_config from the bases, collects decorators (@field_validator, @model_validator, @field_serializer, @computed_field), and generates a core schema that pydantic-core compiles into __pydantic_validator__ and __pydantic_serializer__. If a name cannot be resolved yet, the class is created anyway with __pydantic_complete__ = False and a placeholder validator; the first use raises PydanticUserError: ... is not fully defined; you should define ..., then call ....model_rebuild() (real run). With defer_build=True the build itself waits for first use. Generic parametrisations (Page[int]) are built and cached on first subscription. This is also why FastAPI fails differently: it inspects function signatures with the module's globals at decoration time, cannot see a function-local model, and falls back to treating the parameter as a query parameter (real run: 422 with loc ["query", "item"]).
| Stage | When | Failure you see |
|---|---|---|
| Annotation resolution | Class creation | Incomplete model, PydanticUserError at first use |
| Schema generation | Class creation (or first use with defer_build) | PydanticSchemaGenerationError for unknown types (fix: core schema or arbitrary_types_allowed) |
| Core schema compile | Class creation | SchemaError (e.g. a regex the Rust engine rejects) |
| Validation | Every call | ValidationError |
| Serialisation | Every dump | PydanticSerializationError for values the serialiser cannot handle |
Exact errors, warnings and messages Must-know
Every line below was printed by the saved probes and runs (pipeline/sources/python-typing-pydantic/runs/) or is asserted verbatim by the snippet tests (int_parsing, frozen_instance, parse_obj rows), on Pydantic 2.13.5, pydantic-settings 2.11.0, mypy 1.19.1, FastAPI 0.128.8, CPython 3.9.6.
| Trigger | Exact output |
|---|---|
qty: int ← "two" | {"type": "int_parsing", "loc": ("lines", 0, "qty"), "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "two"} |
StrictLine ← "3" | Input should be a valid integer [type=int_type, input_value='3', input_type=str] |
lines=[] with min_length=1 | List should have at least 1 item after validation, not 0 [type=too_short, ...] |
Unknown key with extra="forbid" | Extra inputs are not permitted [type=extra_forbidden, input_value=True, input_type=bool] |
| Unknown payment kind | Input tag 'cash' found using 'kind' does not match any of the expected tags: 'card', 'bank', 'wallet' [type=union_tag_invalid, ...] |
placedAt: "yesterday" | Input should be a valid datetime or date, input is too short [type=datetime_from_date_parsing, ...] |
assert v > 0, "must be positive" in a validator | {"type": "assertion_error", "msg": "Assertion failed, must be positive"} |
model_validate(domain_obj) without from_attributes | Input should be a valid dictionary or instance of OrderOut [type=model_type] |
| Assignment to a frozen model | type=frozen_instance |
Field type imported under TYPE_CHECKING | PydanticUserError: `Invoice` is not fully defined; you should define `Money`, then call `Invoice.model_rebuild()`. |
typing.TypedDict on 3.9 | PydanticUserError: Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12. |
TypeAdapter(int | None) on 3.9 | TypeError: unsupported operand type(s) for |: 'type' and 'NoneType' |
Field(pattern=r"^(?=.*\d).{8,}$") | SchemaError: Error building "model" validator: (look-ahead unsupported by rust-regex) |
class Config: orm_mode = True | Support for class-based `config` is deprecated, use ConfigDict instead. + * 'orm_mode' has been renamed to 'from_attributes' |
a: Final = 1 in a model | PydanticDeprecatedSince211: Annotation 'a' is marked as final and has a default value. Pydantic treats 'a' as a class variable, but it will be considered as a normal field in V3 ... |
Model.parse_obj(...) | PydanticDeprecatedSince20 (message names model_validate) |
| Settings without required secret | loc ("payment_api_key",), type missing |
Unknown key in .env (default extra="forbid") | 1 validation error for S … extra_forbidden ('app_typo',) |
| FastAPI route with an unresolvable model under the future import | 422 {"detail":[{"type":"missing","loc":["query","amount"],"msg":"Field required","input":null}]}; /openapi.json → 500 |
mypy on static_errors.py | error: Argument 2 to "checkout" has incompatible type "UserId"; expected "OrderId" [arg-type] (and [index], [arg-type], [misc]) |
Storing a model in a JSON column Important
A common shape is a relational row with indexed columns plus the full validated payload as JSON. The snippet's OrderStore does it with SQLite (stdlib sqlite3); the SQL below is the schema and the reporting query it ran, followed by the PostgreSQL version (expected, not run: no PostgreSQL on the build machine). The JSON is always written by model_dump_json(by_alias=True) and read back with model_validate_json, so the column never holds something the model would reject, and old rows written by an earlier model version are re-validated on read.
-- SQLite (real run: tests/test_storage_domain.py)
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')), -- mirrors Literal[...]
payload TEXT NOT NULL CHECK (json_valid(payload)), -- OrderIn.model_dump_json()
placed_at TEXT NOT NULL
);
INSERT INTO orders (email, payload, placed_at) VALUES (?, ?, ?);
SELECT json_extract(payload, '$.payment.kind') AS kind, COUNT(*)
FROM orders GROUP BY kind ORDER BY kind; -- real result: [('card', 1), ('wallet', 1)]
-- PostgreSQL equivalent (expected, not run)
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
payload jsonb NOT NULL,
placed_at timestamptz NOT NULL
);
CREATE INDEX orders_payment_kind ON orders ((payload -> 'payment' ->> 'kind'));
SELECT payload -> 'payment' ->> 'kind' AS kind, count(*) FROM orders GROUP BY 1 ORDER BY 1;With SQLAlchemy 2 or SQLModel the column is a JSON/JSONB column type and the conversion stays explicit at the repository boundary (dump on write, validate on read). Schema changes to the payload are model changes, not migrations, so keep old fields readable (defaults, AliasChoices) or backfill with an Alembic data migration; see SQLAlchemy 2 & SQLModel.
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
| Dicts passed around untyped | KeyError deep in the code; mypy silent (Any) | Model at the boundary | One class |
| First error only | Clients fix one field per round trip | Pydantic collects all errors | None |
| Unknown keys accepted | isAdmin: true stored or acted on | extra="forbid" on input DTOs | Clients must send clean payloads |
| Float money | 0.1 + 0.2 cents lost | Decimal + decimal_places=2 + string serialiser | None |
| Naive datetimes | Times shift by the server's zone | Require an offset (AwareDatetime or an after validator), dump UTC | None |
| Plain union of models | Wrong model picked, six errors for one problem | Discriminated union | A Literal tag |
| Alias config on parent only | Field required on nested fields | Shared base class | None |
TypeAdapter in a function | 5x slower validation | Module-level adapter | None |
Optional[X] without default | "Optional" field is required | = None | None |
| Mutable class-level default | Plain classes share one list; @dataclass with xs: list = [] refuses it (ValueError: mutable default <class 'list'> for field xs is not allowed: use default_factory, real run) | default_factory (Pydantic copies a [] default per instance) | None |
Future import + TYPE_CHECKING import | Incomplete model, or FastAPI query param + 422 | Real import, Ruff runtime-evaluated-base-classes | Import cost |
| Same model for input and output | Clients can set id; responses leak fields | Separate In/Out DTOs | Two classes |
Secrets in repr and logs | API keys in error trackers | SecretStr; hide_input_in_errors for printed errors plus errors(include_input=False) wherever errors are logged or returned | .get_secret_value() calls |
| Settings read lazily | Crash at first use in production | Settings() at startup, required fields | None |
| v1 calls left behind | Deprecation warnings, v3 breakage later | bump-pydantic, warnings as errors in CI | One migration |
Validate once, at the edge
The difference between Before and After: every value that comes from outside goes through one model once, and the rest of the code receives typed objects. In FastAPI the edge is the parameter declaration (Request Validation); in a worker it is Model.model_validate_json(message.body) as the first line of the handler; in a CLI it is @validate_call or a settings model.
Partial updates (PATCH) without overwriting
Declare an update DTO whose fields are all optional, validate the body, then apply only what was sent: changes = patch.model_dump(exclude_unset=True). exclude_none would be wrong here (a client sending "coupon": null wants to clear the coupon); exclude_unset distinguishes "absent" from "null", which the snippet's test_dump_options asserts.
One model, many payload versions
Accept old and new shapes at the same time with a model_validator(mode="before") that rewrites legacy keys (items → lines), AliasChoices for renamed fields, a callable Discriminator for objects without a tag, and a version: Literal[1, 2] field once producers can send it. Remove the shims when the old producers are gone.
Typed configuration that fails fast
A required SecretStr without default, env_nested_delimiter for structured settings, secrets_dir for mounted secrets, and Settings() called during startup: a missing variable stops the deploy instead of the first checkout. Tests construct Settings with explicit values or monkeypatch.setenv.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| HTTP request/response bodies | Pydantic BaseModel (via FastAPI) | extra="forbid" on input, from_attributes on output | Validation + OpenAPI |
| Queue / webhook payloads | BaseModel + model_validate_json | Discriminated union on type | One parse, clear errors |
| Domain entities with rules | @dataclass (or attrs) | Conversion functions from DTOs | No wire coupling |
| Small immutable values | @dataclass(frozen=True) or frozen model | Money as a frozen model if it crosses the wire | Hashable, safe |
| Dict-shaped data, high volume | TypedDict + TypeAdapter | typing_extensions.TypedDict on < 3.12 | Faster than nested models |
| Top-level JSON arrays | TypeAdapter(list[X]) | Module-level | No wrapper model |
| Function arguments from untrusted callers | @validate_call | strict=True for internal APIs | Boundary without HTTP |
| Configuration | pydantic-settings BaseSettings | SecretStr, secrets_dir | Fail fast, typed |
| Internal service contracts | Pydantic in strict mode | Shared models package, versioned | Producer bugs surface |
| Plug-in points / test doubles | Protocol | Small, consumer-owned | Structural, no inheritance |
| Ids that must not mix | NewType | mypy/pyright in CI | Free at runtime |
| Static checking | mypy (strict, Pydantic plugin) or pyright | Both in CI on new code | Catch bugs before running |
When Pydantic vs dataclasses, attrs or TypedDict
| Need | Pydantic v2 | dataclasses | attrs | TypedDict |
|---|---|---|---|---|
| Validate untrusted input | Yes (lax or strict) | No | Opt-in validators | Only through Pydantic |
| Parse JSON directly | model_validate_json | No | Via cattrs | Via TypeAdapter |
| JSON Schema / OpenAPI | Yes | Via Pydantic | No | Via Pydantic |
| Aliases, camelCase | Yes | No | No | No |
| Zero dependencies | No (pydantic, pydantic-core) | Yes (stdlib) | No (one package) | Yes |
| Per-instance cost | Validation every time | Lowest | Low | None (a dict) |
| FastAPI integration | Native | Works (converted) | No | As fields |
Pydantic's own docs position it as a complement: attrs' documentation describes Pydantic as "a capable complement to class building libraries like attrs (or Data Classes!) for parsing and validating untrusted data". The pragmatic split: Pydantic where data crosses a trust boundary, dataclasses or attrs where your own code creates the objects.
In architecture: from a single process to a distributed system
Monolith: one process, one database
One FastAPI app, one PostgreSQL database, one Settings() built at startup. Input DTOs validate every request; output DTOs shape every response; SQLAlchemy 2 or SQLModel models map tables; a thin service layer converts between them. Example: the shop's POST /orders validates OrderIn (camelCase, extra="forbid", discriminated payment), the service builds an Order, the repository writes the row and the JSON payload, and OrderOut is returned with status 201. mypy in CI checks the whole codebase in strict mode; /openapi.json is generated from the same models.
Modular monolith and multiple databases
Each module (catalog, orders, payments) owns its DTOs and its domain objects; modules talk through Python calls that take and return typed objects (dataclasses or frozen models), never raw dicts. A module's public API is a set of Protocols and DTOs in one file, and other modules import only that file (a review rule, or a lint rule on imports). A second database (Redis for carts) stores model_dump_json() text and reads it back with model_validate_json, so a cart written by an older deploy is still validated.
Microservices
Between services the DTO becomes a contract. Two common patterns: a shared, versioned package of Pydantic models (shop-contracts==3.2.0) imported by producer and consumer, or JSON Schema / OpenAPI documents generated by model_json_schema() and published, from which other services (TypeScript, Go) generate their types. Example flow: orders service publishes {"type": "order.paid", "version": 2, ...} on a queue; the shipping service validates it with a discriminated union over type in strict mode and sends invalid messages to a dead-letter queue with err.json() attached. What does not survive the hop: Python-only behaviour (validators that call your database, computed fields, SecretStr masking), lax coercions the other language does not share, and Decimal precision unless it is serialised as a string. Contract evolution rules: add optional fields only, never repurpose a field, accept old names with AliasChoices during a migration (Serialization Formats).
Distributed data: replicas, caches, sharded databases, multi-region
Every copy of the data is a chance for a stale or older shape: a cache entry written before a deploy, a replica row with yesterday's JSON payload, an event replayed from a year-old topic, a region running the previous release. Validating on read (not only on write) with defaults for new fields turns those into normal cases instead of crashes; model_validate_json on cached bytes costs microseconds. Timezones matter more across regions: store UTC (OrderOut serialises with Z), reject naive datetimes at the edge. Idempotency keys and event ids are typed fields (UUID), validated like everything else.
Scaling path: 1×, 10×, 100×
| Load | What changes | Typing and Pydantic practice |
|---|---|---|
| 1× (one process) | Correctness is the problem | Models at every boundary, mypy in CI, separate In/Out DTOs, required settings |
| 10× (several workers or services) | Contracts between teams, rolling deploys | Versioned shared models or published JSON Schema; tolerant readers (defaults, AliasChoices); strict mode for internal contracts |
| 100× (high throughput, many services) | CPU per request, cold starts, schema drift | Reuse TypeAdapters, model_validate_json on bytes, discriminated unions, TypedDict for bulk rows, defer_build for cold starts, schema diffs in CI |
Lab
All commands run from docs/snippets/python/python-typing-pydantic/ with the venv from step 1: either call ~/venvs/ptp/bin/python explicitly (as written below) or source ~/venvs/ptp/bin/activate first; the >>> sessions are ~/venvs/ptp/bin/python started in that directory. The outputs marked "real" were produced on CPython 3.9.6 (macOS, arm64) with the pinned versions.
1. Install and run the tests (real)
mkdir -p /tmp/ptp-build && cp -R pyproject.toml app /tmp/ptp-build/ # build from a copy: no egg-info here
python3 -m venv ~/venvs/ptp # keep the venv outside the repo
(cd /tmp/ptp-build && ~/venvs/ptp/bin/pip install '.[test,dev]') # dev = mypy, attrs, fastapi, httpx
export PYTHONDONTWRITEBYTECODE=1 # no __pycache__; pyproject sets -p no:cacheprovider
~/venvs/ptp/bin/python -m pytest -s
# TypeAdapter reused: 13.2 us/call; rebuilt every call: 65.6 us/call
# model_validate_json: 6.3 us; json.loads + model_validate: 6.8 us; model_validate(dict): 4.8 us; model_dump_json: 7.1 us
# app/static_errors.py:18: error: Argument 2 to "checkout" has incompatible type "UserId"; expected "OrderId" [arg-type]
# ...
# Success: no issues found in 12 source files
# 95 passed in 35.07sThese are the commands that ran (with scratch-directory paths in place of /tmp and ~/venvs; transcript in runs/pytest-fresh-install.txt). The install is made from a copy so no egg-info lands next to the sources; pip install -r requirements.lock reproduces the exact set. With only the test extra (pip install '.[test]') the run is 91 passed, 3 skipped in 0.64s: the mypy, attrs and FastAPI tests skip (real). Most of the 35 s is mypy's cold cache. With uv on Python 3.12+: uv run --extra test --extra dev pytest -s (expected, not run: uv is not installed on the build machine).
2. Lax vs strict in a REPL (real)
>>> from app.models import LaxLine, StrictLine
>>> LaxLine.model_validate({"qty": "3", "price": "9.99", "placed_at": "2026-11-29T10:00:00Z"}).qty
3
>>> StrictLine.model_validate({"qty": "3", "price": "9.99", "placed_at": "2026-11-29T10:00:00Z"})
# 3 validation errors for StrictLine: int_type, is_instance_of, datetime_type
>>> StrictLine.model_validate_json('{"qty": 3, "price": "9.99", "placed_at": "2026-11-29T10:00:00Z"}').price
Decimal('9.99')The full per-type table came from pipeline/sources/python-typing-pydantic/runs/p1_coercion.py; from the snippet directory: ~/venvs/ptp/bin/python ../../../../pipeline/sources/python-typing-pydantic/runs/p1_coercion.py (output saved next to the script).
3. Read a ValidationError (real)
from pydantic import ValidationError
from app.models import OrderIn
try:
OrderIn.model_validate({"customerEmail": "x", "lines": [], "payment": {"kind": "cash"},
"placedAt": "yesterday", "isAdmin": True})
except ValidationError as exc:
print(exc.error_count(), [e["loc"] for e in exc.errors()], [e["type"] for e in exc.errors()])
# 5 [('customerEmail',), ('lines',), ('payment',), ('placedAt',), ('isAdmin',)]
# ['string_pattern_mismatch', 'too_short', 'union_tag_invalid', 'datetime_from_date_parsing', 'extra_forbidden']All five problems come back in one exception; print(exc) gives the multi-line report quoted in ValidationError (runs/lab-steps-output.txt, runs/p2_probes-output.txt).
4. Break the model with the future import (real)
>>> from app import future_trap
>>> future_trap.Invoice.__pydantic_complete__
False
>>> future_trap.Invoice.model_validate({"number": "A-1", "total": {"amount": "1"}})
# PydanticUserError: `Invoice` is not fully defined; you should define `Money`, then call `Invoice.model_rebuild()`.
>>> from app.models import Money; future_trap.Invoice.model_rebuild(_types_namespace={"Money": Money})
TrueThen the FastAPI version: ~/venvs/ptp/bin/python -m pytest tests/test_fastapi_trap.py passes and asserts that the function-local model became loc ["query", "item"] (real, with the fastapi extra).
5. Settings from the environment (real; the Docker secret mount expected, not run)
SHOP_PAYMENT_API_KEY=sk_test SHOP_DB__POOL_SIZE=20 ~/venvs/ptp/bin/python -c "from app.settings import Settings; s = Settings(); print(s.db.pool_size, s.payment_api_key)"
# 20 **********
~/venvs/ptp/bin/python -c "from app.settings import Settings; Settings()"
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
# payment_api_key
# Field required [type=missing, input_value={}, input_type=dict]
docker run --rm -v ./secrets:/run/secrets:ro ... # with secrets_dir="/run/secrets" (expected, not run: no Docker here)6. Static checking (real)
~/venvs/ptp/bin/mypy --config-file pyproject.toml --cache-dir /tmp/mypy-ptp app/static_errors.py
# app/static_errors.py:18: error: Argument 2 to "checkout" has incompatible type "UserId"; expected "OrderId" [arg-type]
# app/static_errors.py:23: error: Value of type "Optional[OrderRow]" is not indexable [index]
# app/static_errors.py:27: error: Argument 3 to "charge" of "FakeGateway" has incompatible type "Literal['GBP']"; expected "Literal['EUR', 'USD', 'IRR']" [arg-type]
# app/static_errors.py:32: error: Cannot assign to final name "RETRIES" [misc]
# Found 4 errors in 1 file (checked 1 source file)
~/venvs/ptp/bin/mypy --config-file pyproject.toml --cache-dir /tmp/mypy-ptp app
# Success: no issues found in 12 source files
pyright app/ # expected, not run (pyright is not installed on the build machine)For PHP/Laravel developers
Laravel splits what Pydantic does in one class across two features. Validation lives in the request: $request->validate([...]) or a Form Request; the docs: "Form requests are custom request classes that encapsulate their own validation and authorization logic", created with php artisan make:request StorePostRequest. Rules are strings ('qty' => 'required|integer|min:1'), all failures are collected and, for JSON requests, "Laravel will automatically format the error messages for you and return a 422 Unprocessable Entity HTTP response". prepareForValidation() is a model mode="before" validator, the after() hook is a mode="after" model validator, bail and #[StopOnFirstFailure] are the opposite of Pydantic's collect-everything default, and $request->validated() / safe()->only([...]) are closer to model_dump(include=...) than to extra="forbid": unknown top-level keys are dropped silently rather than rejected, and for arrays the docs warn that "the validator's validate and validated methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated" unless allowed keys are declared ('payment' => ['array:kind,last4,iban']). Conversion lives on the Eloquent model: "Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model's casts method provides a convenient way of converting attributes to common data types." 'is_admin' => 'boolean', 'options' => 'array', decimal:<precision>, datetime, encrypted, enum casts and AsArrayObject correspond to Pydantic field types, Decimal precision, SecretStr and JSON columns. What the validation rules do not give you is a static type check of your own code or a JSON Schema generated from the rules; on the Python side the same annotations feed mypy/pyright and model_json_schema().
// app/Http/Requests/StoreOrderRequest.php (Laravel 13): the OrderIn model as a Form Request
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool { return $this->user() !== null; } // no Pydantic equivalent (auth is a FastAPI dependency)
protected function prepareForValidation(): void // model_validator(mode="before")
{
$this->merge(['customerEmail' => strtolower(trim((string) $this->customerEmail))]);
}
public function rules(): array
{
return [
'customerEmail' => ['required', 'email', 'max:254'], // Field(max_length=254, pattern=...)
'lines' => ['required', 'array', 'min:1', 'max:50'], // Field(min_length=1, max_length=50)
'lines.*.sku' => ['required', 'regex:/^[A-Z]{3}-\d{4}$/'], // Sku = Annotated[str, AfterValidator(...)]
'lines.*.qty' => ['required', 'integer', 'min:1', 'max:1000'], // Qty = Annotated[int, Field(gt=0, le=1000)]
'payment.kind' => ['required', 'in:card,bank,wallet'], // the discriminator
'payment.last4' => ['required_if:payment.kind,card', 'digits:4'], // Card.last4
'payment.iban' => ['required_if:payment.kind,bank', 'string', 'min:15', 'max:34'],
'placedAt' => ['required', 'date'],
];
}
}
// app/Models/Order.php: casts are the conversion half (Pydantic field types)
class Order extends Model
{
protected function casts(): array
{
return ['total' => 'decimal:2', 'placed_at' => 'immutable_datetime', 'payload' => AsArrayObject::class];
}
}| Laravel / PHP | Python typing / Pydantic |
|---|---|
Form Request rules() | BaseModel fields + Field constraints |
prepareForValidation() | @model_validator(mode="before") |
after() hook | @model_validator(mode="after") |
| Custom rule class | AfterValidator / field_validator / custom type |
bail, #[StopOnFirstFailure] | Not the default; Pydantic collects all errors (FailFast() for sequences) |
$request->validated(), safe()->only() | Validated model / model_dump(include=...); not extra="forbid" (unknown keys dropped, undeclared nested array keys kept) |
422 JSON with errors | ValidationError → FastAPI 422 detail list |
Laravel casts: boolean, integer, decimal:2, datetime, array | Field types with lax coercion |
encrypted cast | SecretStr (masking, not encryption) |
$hidden on a model | Field(exclude=True) / separate output model |
PHP native types (runtime TypeError) | Annotations (not enforced) + Pydantic at the edges |
The Go angle
Go has no runtime validation layer in the language; a struct is a typed record and encoding/json fills it, so Go struct tags do in one string what Pydantic's aliases and Field do: json:"customerEmail,omitempty" is alias plus exclude_none-like behaviour (the encoding/json source documents that the omitempty option omits a field whose value is empty, and also the newer omitzero option). Types are enforced at compile time, so the mypy half of this chapter is free, but json.Unmarshal only checks JSON types: "qty": "2" into an int field is an *UnmarshalTypeError (per decode.go, the error for a JSON value not appropriate for the Go type; Go is strict where Pydantic is lax), unknown keys are ignored unless you call Decoder.DisallowUnknownFields() (its doc comment in stream.go: it makes the decoder return an error when the destination is a struct and the input has keys that match no exported field), and constraints come from a library: go-playground/validator, whose README says "Package validator implements value validations for structs and individual fields based on tags", with tags such as required, gt, min, max, len, oneof, e164 and dive for slices. Its errors are validator.ValidationErrors (all failures, like Pydantic). Discriminated unions are an interface plus a type switch on a Kind field (Interfaces & Type Switches); there is no JSON Schema generator in the standard library. Struct tags and JSON are covered in Structs, Methods & Struct Tags and JSON, XML & Struct Tags.
// The OrderIn model with struct tags (encoding/json + github.com/go-playground/validator/v10)
type OrderLine struct {
SKU string `json:"sku" validate:"required,len=8"` // Pydantic: Sku alias + pattern
Qty int `json:"qty" validate:"gt=0,max=1000"` // Annotated[int, Field(gt=0, le=1000)]
UnitPrice string `json:"unitPrice" validate:"required,numeric"` // Decimal as a string; parse it with math/big or a decimal library
}
type OrderIn struct {
CustomerEmail string `json:"customerEmail" validate:"required,email,max=254"`
Lines []OrderLine `json:"lines" validate:"required,min=1,max=50,dive"` // dive = validate each element
Payment Payment `json:"payment" validate:"required"`
Coupon *string `json:"coupon,omitempty"` // str | None = None
PlacedAt time.Time `json:"placedAt" validate:"required"` // RFC 3339 only, no lax parsing
}
func decodeOrder(r io.Reader) (OrderIn, error) {
var in OrderIn
dec := json.NewDecoder(r)
dec.DisallowUnknownFields() // extra="forbid"
if err := dec.Decode(&in); err != nil { // "qty": "2" fails here: Go is strict, Pydantic lax
return in, err
}
validate := validator.New(validator.WithRequiredStructEnabled())
return in, validate.Struct(in) // validator.ValidationErrors lists every failing field
}| Concern | Python + Pydantic v2 | Go |
|---|---|---|
| Static types | Annotations + mypy/pyright (optional) | Compiler (mandatory) |
| Runtime validation | Pydantic (built from annotations) | go-playground/validator (struct tags) |
| Wire names | alias, alias_generator=to_camel | json:"customerEmail" per field |
| Unknown keys | extra="ignore" default, "forbid" | Ignored by default, DisallowUnknownFields() |
"2" into an int | Accepted in lax mode | *json.UnmarshalTypeError |
| Optional | X | None = None | Pointer or omitempty / omitzero |
| Tagged unions | Field(discriminator=...) | Interface + Kind field + type switch |
| Structural typing | Protocol | Interfaces (implicit) |
| Errors | ValidationError.errors() | validator.ValidationErrors, FieldError |
| JSON Schema | model_json_schema() | Third-party generators |
| Config | pydantic-settings | os.Getenv / envconfig-style libraries |
Common misconceptions
| Belief | Reality |
|---|---|
| Type hints are checked when the code runs | "The Python runtime does not enforce function and variable type annotations"; checkers and Pydantic read them |
| mypy passing means the data is valid | It checks code consistency; Any from json.loads is unchecked; runtime data needs validation |
Optional[X] means the field can be omitted | It means the value can be None; only a default makes it omittable |
from __future__ import annotations is harmless | Runtime readers must resolve strings; TYPE_CHECKING imports and local classes break Pydantic and FastAPI |
X | None works everywhere on 3.9 | Only inside postponed annotations; as an expression it raises TypeError |
NewType and Final do something at runtime | Both are static-only; UserId(5) is the int 5 |
@runtime_checkable checks method signatures | It checks that the names exist |
| A dataclass validates its fields | Nothing in @dataclass examines the annotated types |
| Pydantic validates the input | It guarantees the output; lax mode converts "3" to 3 |
| Lax mode converts anything | 3.5 → int, "1e3" → int, numbers → str all fail |
| Strict mode rejects strings for dates everywhere | JSON input still accepts ISO strings for datetime, Decimal, UUID |
model_dump() is JSON-ready | mode="python" keeps Decimal, datetime, custom objects; use mode="json" |
exclude_unset and exclude_none are the same | Unset = never provided; none = provided or defaulted to None |
| Unknown keys are rejected by default | extra="ignore" on BaseModel; "forbid" is opt-in (BaseSettings defaults to "forbid") |
| Nested models inherit the parent's config | model_config is per class; use a shared base |
| Assignment is validated | Only with validate_assignment=True; model_copy(update=...) is never validated |
A plain Union picks the right model | Smart mode stops early only on an exact type match; dict input to model members tries them all and reports all errors; use a discriminator |
validate_return=True rejects wrong return types | Lax mode converts them; add strict=True |
Creating a TypeAdapter is free | It builds a validator each time; reuse one |
Field(pattern=...) is Python re | Rust regex by default: no look-arounds |
extra="forbid" on settings catches typoed variables | Unmatched environment variables are ignored |
| v1 code that still runs is migrated | Deprecated calls warn, and coercion defaults changed underneath |
Cheat sheet
| Topic | Remember |
|---|---|
| Hints | Metadata; mypy/pyright check statically, Pydantic at runtime |
| Optional | X | None = None (default makes it optional); 3.9: Optional[X] in runtime expressions |
| Future import | Strings everywhere; real imports for runtime-read types; deprecated in 3.14 |
| Literal / Enum | Closed sets; Pydantic validates both |
| Protocol | Structural, consumer-owned, small |
| Generics | Generic[T] / class Page[T] (3.12); ParamSpec in decorators; Self for builders |
| Annotated | Annotated[int, Field(gt=0)]; before/wrap right to left, after left to right |
| Model | class X(BaseModel); validated on construction only |
| Validate | model_validate(obj), model_validate_json(bytes); model_construct = no checks |
| Dump | model_dump(mode="json", by_alias=True, exclude_unset=True), model_dump_json() |
| Lax/strict | Lax default; strict per call/field/model; JSON keeps string dates in strict |
| Aliases | Shared base with alias_generator=to_camel + validate_by_name; AliasChoices for migrations |
| Field | gt ge lt le, min_length max_length, pattern, max_digits, decimal_places, default_factory |
| Validators | after (typed) > before (reshape) > wrap (rare) > plain (replace); model after for cross-field |
| Unions | Field(discriminator="kind") + Literal tags; callable Discriminator + Tag for legacy |
| Config | extra="forbid" in, from_attributes out, frozen for values |
| Errors | Branch on type; loc uses input names; errors(include_input=False) for secrets (hide_input_in_errors covers printing only) |
| Performance | Reuse adapters, validate JSON bytes directly, tagged unions, TypedDict for bulk |
| Migration | model_ prefixes, field_validator/model_validator, ConfigDict, bump-pydantic |
| Settings | init > env > .env > secrets dir > defaults; SecretStr; fail at startup |
| Architecture | DTOs at the edges, plain domain objects inside |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does Python do with a type hint at runtime, and who actually checks it? Must-know
Answer
Answer: Python stores it (in __annotations__) and does nothing else: "The Python runtime does not enforce function and variable type annotations." Static checkers such as mypy and pyright read the hints before the code runs and report inconsistencies; libraries such as Pydantic and FastAPI read them at runtime and build validators from them. A function annotated x: int still runs with "ab". See Type hints.
2 — Is coupon: Optional[str] required in a Pydantic model? What about coupon: str | None = None? Must-know
Answer
Answer: The first is required: Optional only allows the value None, and without a default the key must be present (sending null is fine). The second is optional because of the default. Optional[X] and X | None are the same type; on Python 3.9 the | spelling works only inside postponed annotations (from __future__ import annotations, plus eval-type-backport for Pydantic). See Optional and Union.
3 — What is the difference between lax mode and strict mode, and why does strict JSON still accept "2026-11-29T10:00:00Z" for a datetime? Must-know
Answer
Answer: Lax mode (the default) converts well-defined representations ("3" → 3, "yes" → True, ISO strings → datetime); strict mode accepts only values of the exact type and fails with int_type, bool_type, datetime_type. JSON has no date, Decimal, UUID or tuple types, so strict mode on JSON input accepts their standard string/array forms. Strict mode can be set per call, per field or per model. See Lax and strict.
4 — In which order do validators run, and which one would you use to turn "" into None, to enforce "end after start", and to replace type checking completely? Must-know
Answer
Answer: model_validator(mode="before") on the raw input, then per field: before validators (and wrap validators around) the core Rust type/constraint check, then after validators; finally model_validator(mode="after") on the instance. "" → None is a field_validator(mode="before") (or BeforeValidator); "end after start" is a model_validator(mode="after") returning self; a PlainValidator replaces the core check. In Annotated, before/wrap validators run right to left, after validators left to right. See Validators.
5 — How do you accept customerEmail on the wire, use customer_email in Python, and return camelCase in responses? Must-know
Answer
Answer: alias_generator=to_camel on a shared base model (nested models do not inherit config), validate_by_name=True (or populate_by_name=True before 2.11) to accept Python names too, and model_dump(by_alias=True) or serialize_by_alias=True (2.11+) on output. For renamed fields, validation_alias=AliasChoices("new", "old"). See Aliases.
6 — Why prefer a discriminated union over a plain Union[Card, BankTransfer, Wallet]? Important
Answer
Answer: With Field(discriminator="kind") Pydantic reads the tag and validates only the matching model: one lookup, errors located under that member (2 errors for a bad card in the snippet) and a JSON Schema with oneOf + discriminator mapping for client generators. A plain union tries every member and reports all of them (6 errors for the same payload). For payloads without a tag, use a callable Discriminator with Tag. See Discriminated unions.
7 — What does from __future__ import annotations change, and how can it break a Pydantic model or a FastAPI route? Important
Answer
Answer: It stores every annotation as a string (PEP 563). Pydantic and FastAPI must resolve the strings at runtime in the module's namespace; a type imported only under if TYPE_CHECKING: or defined inside a function cannot be found. Pydantic then leaves the model incomplete (... is not fully defined; you should define Money, then call model_rebuild()), and FastAPI treats the unresolved parameter as a required query parameter (422 loc ["query", "item"]). Fix: real imports, module-level models, model_rebuild(), Ruff's runtime-evaluated-base-classes. See the future import.
8 — When would you use TypeAdapter, and what is the most common performance mistake with it? Important
Answer
Answer: For types that are not BaseModel subclasses: list[Model] bodies, TypedDict rows, unions, dict[str, int], with validate_python, validate_json, dump_json and json_schema. The mistake is constructing it inside a function: each construction builds a validator and serialiser (66 µs vs 13 µs per call in the snippet run). Create adapters once at module level. See TypeAdapter.
9 — A PATCH endpoint must update only the fields the client sent, including setting coupon to null. Which dump option do you use and why not the other? Important
Answer
Answer: model_dump(exclude_unset=True): it keeps exactly the fields present in the input (tracked in model_fields_set), including those explicitly set to None. exclude_none=True would drop "coupon": null and make clearing impossible, and would also drop omitted-but-defaulted None fields only by accident. See Serialization and Partial updates.
10 — What is the priority order of pydantic-settings sources, and what does env_nested_delimiter="__" do? Important
Answer
Answer: Highest first: CLI arguments (if enabled), arguments to the Settings(...) initialiser, environment variables, the dotenv file, the secrets directory, field defaults. env_nested_delimiter="__" maps SHOP_DB__POOL_SIZE=20 onto settings.db.pool_size (with env_prefix="SHOP_"). Required fields without defaults make the app fail at startup with a missing error, which is the point. See pydantic-settings.
11 — Why keep a domain object separate from the Pydantic DTOs, and when is it fine not to? Good to know
Answer
Answer: DTOs describe wire formats (aliases, extra, JSON quirks) and change with the API; domain objects hold rules and invariants (pay() once, totals) and change with the business. Merging them couples the two and re-validates internal data. For CRUD services with no real rules, using the DTO (or a SQLModel table model) directly is a reasonable simplification until input and output diverge. See DTO vs domain object.
12 — Name four v1 patterns you would find in an old codebase and their v2 replacements. Good to know
Answer
Answer: Model.parse_obj(d) → model_validate(d); .dict() / .json() → model_dump() / model_dump_json(); @validator / @root_validator → @field_validator / @model_validator; class Config: orm_mode = True → model_config = ConfigDict(from_attributes=True); also parse_obj_as → TypeAdapter, __root__ → RootModel, GenericModel → BaseModel + Generic, regex= → pattern=. v1 names still run in 2.x with PydanticDeprecatedSince20 warnings; bump-pydantic automates most rewrites. See Migration.
Glossary
| Term | Meaning |
|---|---|
| Type hints | Annotations on names (x: int, -> str) that Python stores but does not enforce |
| Gradual typing | Adding annotations incrementally; unannotated code is treated as Any |
| mypy | Static type checker; skips unannotated functions unless --check-untyped-defs; Pydantic plugin pydantic.mypy |
| pyright | Microsoft's static type checker (its configuration docs also cover Pylance); checks unannotated code by default |
Any | The type that switches checking off in both directions |
Optional[X] | X or None; says nothing about omission |
Union[X, Y] | Either type; X | Y since 3.10 (PEP 604) |
| X | None | PEP 604 spelling of Optional[X]; a runtime TypeError on 3.9 outside postponed annotations |
from __future__ import annotations | PEP 563: store annotations as strings; deprecated in 3.14 (deferred evaluation, PEP 649/749) |
TYPE_CHECKING | Constant that is True only for type checkers; imports under it do not exist at runtime |
Literal | Type of exact values (PEP 586); validated by Pydantic (literal_error) |
TypedDict | Shape of a dict (PEP 589); a plain dict at runtime; use typing_extensions for Pydantic on < 3.12 |
NotRequired | TypedDict key that may be absent (PEP 655, 3.11) |
Protocol | Structural interface (PEP 544) |
| Structural subtyping | Compatibility by shape (methods/attributes), not by inheritance |
Generic / TypeVar | Type parameters for classes and functions |
ParamSpec | Type variable for a callable's parameter list (PEP 612) |
NewType | Distinct static type over an existing runtime type |
Final | Name that must not be reassigned (PEP 591); static only |
overload | Several static signatures for one runtime function |
Self | "An instance of the current class" (PEP 673, 3.11) |
TypeAlias | Explicit alias annotation (PEP 613, 3.10) |
| type statement | type X = ... (PEP 695, 3.12): lazily evaluated TypeAliasType |
Annotated | Annotated[T, *metadata] (PEP 593): type plus metadata for runtime tools |
| dataclass | Stdlib decorator generating __init__/__repr__/__eq__; no type checks |
| NamedTuple | Tuple subclass with named fields |
| attrs | Third-party class builder with opt-in validators and converters |
| Pydantic v2 | Validation and serialisation library driven by type hints, core in Rust |
| pydantic-core | Rust engine of Pydantic v2 (validator + serializer); now in the main pydantic repository |
| Rust | Language of pydantic-core; validation for most types runs there |
| jiter | The JSON parser used by Pydantic |
BaseModel | Base class for Pydantic models |
| Core schema | Pydantic's internal description of a type, compiled by pydantic-core |
| lax mode | Default validation mode: converts well-defined representations |
| strict mode | Only exact types (JSON exceptions for dates, decimals, UUIDs, tuples) |
| coercion | Converting input to the field type ("3" → 3) |
| conversion table | The docs' per-type list of accepted inputs in lax/strict, Python/JSON |
model_validate | Validate a Python object into a model |
model_validate_json | Parse and validate JSON in one Rust pass |
model_construct | Create without validation |
model_dump | Model to dict (mode="python" or "json") |
model_dump_json | Model to JSON text |
exclude_unset | Dump only fields that were provided |
exclude_none | Dump without None values |
by_alias | Dump using aliases |
| alias | Field name on the wire, both directions |
validation_alias | Input-only name(s); AliasChoices, AliasPath |
serialization_alias | Output-only name |
alias_generator | Function generating aliases for every field |
to_camel | pydantic.alias_generators.to_camel: customer_email → customerEmail |
populate_by_name / validate_by_name | Accept Python names besides aliases (validate_by_name since 2.11) |
Field | Per-field defaults, constraints, aliases, docs |
| constraints gt ge lt le | Numeric bounds in Field/Annotated |
| min_length max_length | Length bounds for strings and collections |
pattern | Regex for strings (rust-regex by default) |
default_factory | Callable producing a fresh default |
computed_field | Property included in serialisation and the serialization schema |
field_validator | Validator for one or more fields; modes before/after/wrap/plain |
model_validator | Validator for the whole model; modes before/after/wrap |
| mode before after wrap | When a validator runs relative to the core check |
AfterValidator / BeforeValidator / WrapValidator / PlainValidator | The same modes as reusable Annotated metadata |
field_serializer / model_serializer | Custom serialisation of a field / the whole model |
| discriminated union | Union selected by a tag field (Field(discriminator=...)) |
Discriminator / Tag | Callable discriminator and member labels |
| generic models | BaseModel subclasses with type parameters (Page[T]) |
RootModel | Model whose value is a single non-dict value (.root) |
TypeAdapter | Validation, serialisation and schema for any type |
validate_call | Decorator validating function arguments (and optionally the return) |
model_config / ConfigDict | Per-model configuration |
| extra forbid ignore allow | What happens to unknown keys |
frozen | Faux-immutable: no attribute assignment, __hash__ generated (works only if all field values are hashable); nested mutable values can still change |
from_attributes | Read objects by attribute (v1 orm_mode) |
| JSON Schema | Standard description of JSON data; model_json_schema() (Draft 2020-12) |
| custom types | Types Pydantic learns through a core schema |
GetPydanticSchema | Annotated helper supplying a core schema for a foreign type |
ValidationError | Exception carrying all validation errors |
errors() | List of error dicts with loc type msg input (plus ctx, url) |
| error types | Stable codes such as missing, int_parsing, extra_forbidden |
| performance | Rust validation is cheap; schema building, Python callbacks and dict round trips are not |
defer_build | Build validator/serializer on first use |
| v1 to v2 migration | Renamed methods, new validators and config, changed coercions; bump-pydantic |
parse_obj deprecated | v1 method; use model_validate |
| pydantic-settings | Package with BaseSettings for typed configuration |
BaseSettings / SettingsConfigDict | Settings model and its config |
env_prefix | Prefix for environment variable names |
env_nested_delimiter | Separator mapping env names onto nested fields |
secrets_dir | Directory of one-file-per-secret values |
| dotenv | .env file source, below environment variables in priority |
SecretStr | String masked in repr; .get_secret_value() reads it |
| DTO | Data transfer object: the shape of data at a boundary |
| Domain object | Object holding business rules and invariants |
| DTO vs domain object | Pydantic at the edges, plain classes in the core |
| Go struct tags | json:"name,omitempty" / validate:"gt=0" strings on Go struct fields |
| go-playground validator | Go library validating structs from validate tags |
| Laravel Form Request | Request class with rules(), authorize(), prepareForValidation() |
| Laravel casts | Eloquent casts() converting attributes to types |
| FastAPI / Starlette / Uvicorn | The web framework built on Pydantic, its ASGI toolkit, and the server |
| SQLAlchemy / SQLModel / Alembic | ORM, Pydantic-based ORM models, and migrations |
| pytest / httpx | Test runner used by the snippets; HTTP client used by FastAPI's TestClient |
References
- Python,
typing— Support for type hints: https://docs.python.org/3/library/typing.html - Python,
dataclasses: https://docs.python.org/3/library/dataclasses.html - Python, Annotations Best Practices (HOWTO): https://docs.python.org/3/howto/annotations.html
- Python,
collections(namedtuple): https://docs.python.org/3/library/collections.html - What's New in Python 3.9 (PEP 585, PEP 593): https://docs.python.org/3/whatsnew/3.9.html
- What's New in Python 3.10 (PEP 604): https://docs.python.org/3/whatsnew/3.10.html
- What's New in Python 3.11 (Self, LiteralString): https://docs.python.org/3/whatsnew/3.11.html
- What's New in Python 3.12 (PEP 695 type statement): https://docs.python.org/3/whatsnew/3.12.html
- What's New in Python 3.13 (PEP 696, 705, 742): https://docs.python.org/3/whatsnew/3.13.html
- What's New in Python 3.14 (PEP 649/749 deferred annotations): https://docs.python.org/3/whatsnew/3.14.html
- Typing specification: https://typing.python.org/en/latest/spec/index.html
- typing_extensions documentation: https://typing-extensions.readthedocs.io/en/latest/
- PEP 3107 – Function Annotations: https://peps.python.org/pep-3107/
- PEP 483 – The Theory of Type Hints: https://peps.python.org/pep-0483/
- PEP 484 – Type Hints: https://peps.python.org/pep-0484/
- PEP 526 – Syntax for Variable Annotations: https://peps.python.org/pep-0526/
- PEP 544 – Protocols: Structural subtyping: https://peps.python.org/pep-0544/
- PEP 563 – Postponed Evaluation of Annotations: https://peps.python.org/pep-0563/
- PEP 585 – Type Hinting Generics In Standard Collections: https://peps.python.org/pep-0585/
- PEP 586 – Literal Types: https://peps.python.org/pep-0586/
- PEP 589 – TypedDict: https://peps.python.org/pep-0589/
- PEP 591 – Final: https://peps.python.org/pep-0591/
- PEP 593 – Flexible function and variable annotations (Annotated): https://peps.python.org/pep-0593/
- PEP 604 – Allow writing union types as X | Y: https://peps.python.org/pep-0604/
- PEP 612 – Parameter Specification Variables: https://peps.python.org/pep-0612/
- PEP 613 – Explicit Type Aliases: https://peps.python.org/pep-0613/
- PEP 649 – Deferred Evaluation Of Annotations Using Descriptors: https://peps.python.org/pep-0649/
- PEP 655 – Required and NotRequired for TypedDict: https://peps.python.org/pep-0655/
- PEP 673 – Self Type: https://peps.python.org/pep-0673/
- PEP 695 – Type Parameter Syntax: https://peps.python.org/pep-0695/
- PEP 749 – Implementing PEP 649: https://peps.python.org/pep-0749/
- mypy, Getting started: https://mypy.readthedocs.io/en/stable/getting_started.html
- mypy, Protocols and structural subtyping: https://mypy.readthedocs.io/en/stable/protocols.html
- mypy, Using mypy with an existing codebase: https://mypy.readthedocs.io/en/stable/existing_code.html
- pyright, Differences from mypy: https://raw.githubusercontent.com/microsoft/pyright/main/docs/mypy-comparison.md
- pyright, Configuration: https://raw.githubusercontent.com/microsoft/pyright/main/docs/configuration.md
- Pydantic, Why use Pydantic: https://docs.pydantic.dev/latest/why/
- Pydantic, Models: https://docs.pydantic.dev/latest/concepts/models/
- Pydantic, Fields: https://docs.pydantic.dev/latest/concepts/fields/
- Pydantic, Validators: https://docs.pydantic.dev/latest/concepts/validators/
- Pydantic, Serialization: https://docs.pydantic.dev/latest/concepts/serialization/
- Pydantic, JSON Schema: https://docs.pydantic.dev/latest/concepts/json_schema/
- Pydantic, Alias: https://docs.pydantic.dev/latest/concepts/alias/
- Pydantic, Configuration: https://docs.pydantic.dev/latest/concepts/config/
- Pydantic, Strict Mode: https://docs.pydantic.dev/latest/concepts/strict_mode/
- Pydantic, Conversion Table: https://docs.pydantic.dev/latest/concepts/conversion_table/
- Pydantic, Unions: https://docs.pydantic.dev/latest/concepts/unions/
- Pydantic, Type Adapter: https://docs.pydantic.dev/latest/concepts/type_adapter/
- Pydantic, Validation Decorator: https://docs.pydantic.dev/latest/concepts/validation_decorator/
- Pydantic, Performance: https://docs.pydantic.dev/latest/concepts/performance/
- Pydantic, Dataclasses: https://docs.pydantic.dev/latest/concepts/dataclasses/
- Pydantic, Types: https://docs.pydantic.dev/latest/concepts/types/
- Pydantic, Forward Annotations: https://docs.pydantic.dev/latest/concepts/forward_annotations/
- Pydantic, Experimental (jiter, partial JSON): https://docs.pydantic.dev/latest/concepts/experimental/
- Pydantic, Settings Management: https://docs.pydantic.dev/latest/concepts/pydantic_settings/
- Pydantic API, BaseModel: https://docs.pydantic.dev/latest/api/base_model/
- Pydantic API, Functional Validators: https://docs.pydantic.dev/latest/api/functional_validators/
- Pydantic API, Functional Serializers: https://docs.pydantic.dev/latest/api/functional_serializers/
- Pydantic API, Configuration (
ConfigDict): https://docs.pydantic.dev/latest/api/config/ - Pydantic API, Types: https://docs.pydantic.dev/latest/api/types/
- Pydantic, Validation Errors: https://docs.pydantic.dev/latest/errors/validation_errors/
- Pydantic, Error Handling: https://docs.pydantic.dev/latest/errors/errors/
- Pydantic, Usage Errors: https://docs.pydantic.dev/latest/errors/usage_errors/
- Pydantic, Migration Guide: https://docs.pydantic.dev/latest/migration/
- Pydantic, Version Policy: https://docs.pydantic.dev/latest/version-policy/
- Pydantic release history (HISTORY.md): https://raw.githubusercontent.com/pydantic/pydantic/main/HISTORY.md
- pydantic-core README (archived repository): https://raw.githubusercontent.com/pydantic/pydantic-core/main/README.md
- pydantic-settings README: https://raw.githubusercontent.com/pydantic/pydantic-settings/main/README.md
- PyPI JSON, pydantic: https://pypi.org/pypi/pydantic/json
- PyPI JSON, pydantic-settings: https://pypi.org/pypi/pydantic-settings/json
- PyPI JSON, mypy: https://pypi.org/pypi/mypy/json
- attrs, Why not…: https://www.attrs.org/en/stable/why.html
- attrs, Overview: https://www.attrs.org/en/stable/overview.html
- Ruff, typing-only-first-party-import (TC001): https://docs.astral.sh/ruff/rules/typing-only-first-party-import/
- FastAPI, Python Types Intro: https://fastapi.tiangolo.com/python-types/
- FastAPI, Request Body: https://fastapi.tiangolo.com/tutorial/body/
- FastAPI, Settings and Environment Variables: https://fastapi.tiangolo.com/advanced/settings/
- FastAPI, Release Notes (0.100.0 Pydantic v2, 0.126.0 drops v1): https://fastapi.tiangolo.com/release-notes/
- Laravel 13, Validation (Form Requests): https://laravel.com/docs/13.x/validation
- Laravel 13, Eloquent: Mutators & Casting: https://laravel.com/docs/13.x/eloquent-mutators
- go-playground/validator README: https://raw.githubusercontent.com/go-playground/validator/master/README.md
- Go source,
encoding/json/encode.go(struct tags,omitempty,omitzero): https://go.dev/src/encoding/json/encode.go - Go source,
encoding/json/decode.go(UnmarshalTypeError): https://go.dev/src/encoding/json/decode.go - Go source,
encoding/json/stream.go(DisallowUnknownFields): https://go.dev/src/encoding/json/stream.go