Skip to content

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 forGo to
The tables you can memorise in one minuteEverything in one minute
Why types, and why runtime validation on topWhy it exists
PEP 3107 (2006) to Pydantic 2.14 (2026)Where it comes from
A before/after order payloadPython
Type hints, gradual typing, mypy, pyrightType hints and static checkers
Optional, Union, X | None, from __future__ import annotationsOptional, Union and the future import
Literal, Final, NewTypeLiteral, Final, NewType
TypedDict, NotRequiredTypedDict
Protocol, duck typing for the checkerProtocol and structural subtyping
Generic, TypeVar, ParamSpec, Self, overloadGenerics, 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 PydanticFive ways to declare a record
BaseModel, pydantic-core, RustBaseModel and pydantic-core
"3" becomes 3? lax mode vs strict modeLax mode, strict mode, the conversion table
model_validate, model_validate_json, model_constructValidating input
model_dump, exclude_unset, by_alias, serializersSerialization
camelCase on the wire, snake_case in PythonAliases
Field(gt=0, max_length=20, pattern=...)Field and constraints
field_validator, model_validator, modesValidators
{"kind": "card"} picks the modelDiscriminated unions
Page[T], RootModel[list[str]]Generic models and RootModel
Validate a list[...] or a function's argumentsTypeAdapter and validate_call
extra, frozen, from_attributesmodel_config and ConfigDict
OpenAPI from modelsJSON Schema
A type Pydantic does not knowCustom types and GetPydanticSchema
errors(), loc, type, msg, inputValidationError
How fast, and how to keep it fastPerformance and defer_build
parse_obj, .dict(), orm_modev1 to v2 migration
Environment variables, .env, secretspydantic-settings
Where Pydantic belongs in the architectureDTO vs domain object
What happens inside one model_validate callMechanics
The common bugs and their fixesSolving the classic problems
Pydantic or a dataclass or a TypedDict?Choosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
Form Requests and $castsFor PHP/Laravel developers
Struct tags and go-playground/validatorThe 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.

ConstructMeaningSinceChecked by mypy/pyrightEnforced by Pydantic at runtime
x: intAnnotation3.0 (functions), 3.6 (variables)YesYes, with lax-mode conversion
Optional[int] / int | Noneint or None3.5 / 3.10YesYes
Union[int, str] / int | strEither type3.5 / 3.10YesYes (smart mode)
Literal["EUR", "USD"]Exactly these values3.8YesYes
FinalNever reassigned3.8YesNo
NewType("UserId", int)Distinct static type, same runtime value3.5.2YesValidated as int
TypedDictShape of a dict3.8YesYes (typing_extensions version on < 3.12)
Protocol"Has these methods"3.8YesNo (only isinstance with @runtime_checkable, names only)
Generic[T], TypeVarType parameters3.5YesYes, on BaseModel generics
ParamSpecA callable's parameter list3.10YesNo
Self"The class this method is called on"3.11YesNo
@overloadSeveral signatures, one implementation3.5YesNo
TypeAlias / type X = ...Named alias3.10 / 3.12YesYes (the aliased type)
Annotated[T, meta]T plus metadata3.9T onlyYes: Field, validators, Strict

Pydantic v2 in one table.

TaskAPIPlain words
Declare a modelclass OrderIn(BaseModel): ...Fields from annotations
Python object to modelOrderIn.model_validate(data)Validate a dict or object
JSON text to modelOrderIn.model_validate_json(text)Parse and validate in Rust in one pass
Trusted data, no checksOrderIn.model_construct(**data)Skip validation
Model to dictm.model_dump(mode="python" | "json")mode="json" gives JSON-safe values
Model to JSONm.model_dump_json(by_alias=True)Returns str, serialised in Rust (TypeAdapter.dump_json returns bytes)
Only what the client sentmodel_dump(exclude_unset=True)Partial updates (PATCH)
Drop None valuesmodel_dump(exclude_none=True)Compact output
Copy with changesm.model_copy(update={...})Not validated
JSON SchemaOrderIn.model_json_schema()What FastAPI puts in OpenAPI
Non-model typesTypeAdapter(list[OrderLine])Same engine for any type
Validate function arguments@validate_callPydantic at a function boundary
Configurationmodel_config = ConfigDict(...)Per-model behaviour
Settingsclass Settings(BaseSettings)Environment variables to typed config

Validators: which mode sees what. Real order from the snippet run (tests/test_models.py).

ValidatorSeesRunsTypical use
@model_validator(mode="before")Raw input (dict, object, anything)First, once per modelRename legacy keys, unwrap envelopes
BeforeValidator / @field_validator(mode="before")Raw field valueBefore the core type check"" → None, strip, split CSV
WrapValidator / mode="wrap"Raw value + handlerAround the core checkFallbacks, truncation, timing
core validator (Rust)Raw valueType + coercion + Field constraintsAlways, unless replaced
PlainValidator / mode="plain"Raw valueInstead of the core checkA completely custom rule
AfterValidator / @field_validator (default "after")Typed valueAfter the core checkBusiness rules on a valid value
@model_validator(mode="after")The built instanceLastCross-field rules

Config keys you will set.

KeyDefaultEffect
extra"ignore" (BaseModel), "forbid" (BaseSettings)"ignore", "forbid" (error extra_forbidden) or "allow" (kept in model_extra)
strictFalseStrict mode for every field
frozenFalseAssignment 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_attributesFalseRead objects (ORM rows, dataclasses) by attribute
alias_generatorNonee.g. to_camel: customer_email ↔ customerEmail
populate_by_name / validate_by_name (2.11+)FalseAccept the Python name as well as the alias
serialize_by_alias (2.11+)FalseDump by alias without passing by_alias=True
validate_assignmentFalseRe-validate on m.x = ...
str_strip_whitespaceFalseStrip strings before validation
defer_buildFalseBuild 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 itShape is a class with typed fields
First error stops the checkAll errors in one ValidationError
int("2.7") crashes, int(2.7) truncates silentlyint_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 Decimalmodel_dump_json() with the same field rules
Nothing for the type checkermypy/pyright see real classes and types
Docs written by handmodel_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 ​

  1. "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.
  2. "Pydantic validates that the input is correct." It builds an output that is correct. In the default lax mode "3" becomes 3, "yes" becomes True and "2026-11-29" becomes a datetime; the input was not "valid" in a strict sense, but the model is. If conversion is not what you want, use strict mode.
  3. "One Pydantic model per resource is enough." Input and output have different rules (an id the client must not send, a password the API must not return, a PATCH where every field is optional). Separate input DTOs, output DTOs and the domain object; FastAPI's response_model and exclude_unset exist 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-19

Python ​

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.

py
"""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:

py
"""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.

py
"""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: datetime

The domain object is deliberately a plain dataclass: it has behaviour (pay(), total) and no wire format.

py
"""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:

py
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",
    }
py
"""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) == order

The 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:

toml
[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:

py
"""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 row

Type 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 CI

Real 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.

mypypyright
OriginThe checker the PEP 484 era grew up withMicrosoft; its configuration docs describe the same settings in Pylance (VS Code)
Unannotated functionsSkipped unless --check-untyped-defsChecked by default
Strict switchstrict = true in [tool.mypy]typeCheckingMode = "strict"
Pydantic supportpydantic.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 here1.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.

py
"""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.

Spelling3.93.10+3.14Note
Optional[int]YesYesYesStill valid; X | None preferred
int | None in an annotationOnly with the future import (and eval-type-backport for Pydantic)YesYes
int | None as an expression (alias, isinstance, TypeAdapter)TypeErrorYesYesReal run on 3.9.6
list[int] (PEP 585)YesYesYesList[int] deprecated alias
from __future__ import annotationsStringsStringsDeprecated, still worksRemoval not before 3.13 end of life (2029)
Forward reference "Order"QuotesQuotesNot 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:

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
py
"""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")
py
"""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 app

Literal, 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 int

Real 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.

ConstructStatic effectPython runtimePydantic
Literal["a", "b"]Only those values type-checkNothingliteral_error for other values; JSON Schema enum
FinalNo reassignment, no overrideNothinga: 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 typeIdentity functionValidated as the base type
Enum / str, EnumMembers onlyReal objectsValidated; 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].

NeedTypedDictBaseModel
Runtime typedictModel instance
ValidationOnly via TypeAdapter / as a fieldAlways
Methods, computed fieldsNoYes
Speed of validationFaster (no instance creation)Slower
Optional keystotal=False / NotRequiredDefaults

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 involved

Real 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).

Protocolabc.ABCGo interface
Satisfied byMatching shapeInheritance or register()Matching method set
CheckedStaticallyAt instantiation (abstract methods)At compile time
Runtime isinstanceOnly with @runtime_checkable, names onlyYesType assertion
Pydantic field typeNeeds arbitrary_types_allowed and validates nothing structuralSamen/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 needed

Real 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].

Feature3.9 spelling3.12+ spelling
Type variableT = TypeVar("T")def f[T](x: T) -> T
Generic classclass Page(Generic[T])class Page[T]
BoundedTypeVar("N", bound=Number)[N: Number]
ParamSpectyping_extensions.ParamSpecdef deco[**P, R](f: Callable[P, R])
Selftyping_extensions.Selftyping.Self (3.11+)
Generic Pydantic modelclass 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
# 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 = None
1    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 union

Real 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.

FormSinceLazyRecursive without quotes
X = Union[...]3.5NoNo
X: TypeAlias = ...3.10NoNo
type X = ...3.12YesYes

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.

MetadataRead byEffect
Field(gt=0, max_length=...)PydanticConstraints, aliases, defaults, docs
AfterValidator(f) / BeforeValidator(f) / WrapValidator(f) / PlainValidator(f)PydanticValidation steps
PlainSerializer(f) / WrapSerializer(f)PydanticSerialisation steps
Strict()PydanticStrict mode for this type
Discriminator(...), Tag(...)PydanticTagged unions
Query(), Path(), Body(), Header(), Depends()FastAPIParameter source and dependencies
Mapped[...] annotationsSQLAlchemy 2 / SQLModelColumn 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).

py
"""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=2

Real 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).

dataclassNamedTupleTypedDictattrs 26.1Pydantic v2
Validates typesNoNoNoOpt-in per fieldYes
Converts "2" → 2NoNoNoOpt-in converter=Yes (lax mode)
Immutable optionfrozen=TrueAlwaysNo@attrs.frozenfrozen=True
JSON in/outasdict + json_asdictis a dictcattrsmodel_dump_json / model_validate_json
JSON SchemaNoNoVia PydanticNoYes
Runtime costLowestLowestNoneLowValidation 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 ValidationError

Real 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 / attributePurpose
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_extraIntrospection
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)).

Same input, three outcomes (pydantic 2.13.5, real run)input to field typelax (default)strict, Python inputstrict, JSON input"3" to int3int_typeint_type3.0 to int3int_typeint_type3.5 to intint_from_floatint_typeint_type"yes" to boolTruebool_typebool_type1 to float1.01.0 (int is allowed)1.0ISO string to datetimedatetimedatetime_typedatetime (JSON has no date type)"1.10" to DecimalDecimal('1.10')is_instance_ofDecimal('1.10')[1, 2] to tuple[int, ...](1, 2)tuple_type(1, 2) (JSON has only arrays)per callmodel_validate(x, strict=True)per fieldField(strict=True), StrictInt, Strict()per modelConfigDict(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 too

Real 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 ← inputLax, PythonStrict, PythonLax, JSONStrict, JSON
int ← "3"3int_type3int_type
int ← 3.03int_type3int_type
int ← 3.5int_from_floatint_typeint_from_floatint_type
int ← True1int_type1int_type
int ← "3.0"3int_type3int_type
float ← 11.01.01.01.0
float ← "nan"nanfloat_typenanfloat_type
bool ← "yes", "on", "1", "y", 1Truebool_typeTruebool_type
bool ← "maybe", 2bool_parsingbool_typebool_parsingbool_type
str ← 3string_typestring_typestring_typestring_type
str ← b"ab""ab"string_typen/an/a
Decimal ← "1.10"Decimal('1.10')is_instance_ofDecimal('1.10')Decimal('1.10')
datetime ← ISO stringdatetimedatetime_typedatetimedatetime
datetime ← unix secondsdatetime (UTC)datetime_typedatetimedatetime_type
datetime ← "2026-11-29"naive midnightdatetime_typenaive midnightdatetime_parsing
date ← "2026-11-29T00:00:00Z"datedate_typedatedate_parsing
UUID ← stringUUIDis_instance_ofUUIDUUID
list[int] ← tuple or setlistlist_typen/an/a
tuple[int, ...] ← listtupletuple_typetupletuple
Enum ← valuememberis_instance_ofmembermember

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).

py
"""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"] == expected

Validating 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_invalid

Real 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.

InputMethodNotes
dict, list, objectsmodel_validatefrom_attributes=True for objects
str / bytes JSONmodel_validate_jsonFastest path, JSON strict rules
dict[str, str] (form, query)model_validate_stringsTreats values as JSON strings
Trusted valuesmodel_constructSets model_fields_set, no validation
Many itemsTypeAdapter(list[Model]).validate_jsonOne 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 / toolEffect
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_unsetOnly fields that were provided
exclude_defaultsDrop fields equal to their default
exclude_noneDrop None values
Field(exclude=True)Never serialise this field
@field_serializer("x")Custom output for one field (mode="plain" or "wrap")
@model_serializerCustom output for the whole model (mode="plain" or "wrap")
PlainSerializer / WrapSerializer in AnnotatedReusable serialisers
@computed_fieldProperty 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).

NeedUse
Same alias in and outField(alias="customerEmail")
Accept several input namesvalidation_alias=AliasChoices(...)
Read a nested keyvalidation_alias=AliasPath(...)
Different output nameserialization_alias=...
camelCase everywherealias_generator=to_camel on a shared base
Accept Python names toovalidate_by_name=True (2.11+) / populate_by_name=True
Output by alias by defaultserialize_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_mismatch

Real 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.

ConstraintApplies toError type
gt / ge / lt / lenumbers, datesgreater_than, greater_than_equal, less_than, less_than_equal
multiple_ofnumbersmultiple_of
min_length / max_lengthstrstring_too_short / string_too_long
min_length / max_lengthlist, set, dicttoo_short / too_long
patternstrstring_pattern_mismatch
max_digits / decimal_placesDecimaldecimal_max_digits / decimal_max_places
strict=Trueanyint_type, string_type …
frozen=True (field)anyfrozen_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).

One model_validate call: where each validator runsmodel_validate(dict)Python objectsmodel_validate_json(str)JSON parsed in Rust (jiter)model_validatormode="before": raw datafor each field (all fields, errors collected)BeforeValidator / field_validator(mode="before")WrapValidator: code around handler(value)core validator (pydantic-core, Rust)type + coercion (lax/strict) + Field constraintsAfterValidator / field_validator(mode="after")PlainValidator replaces the whole core boxmodel_validator(mode="after"): the instancecross-field rules, return selfOrderIn instancetypes guaranteedany failure: ONE ValidationErrorerrors(): [{type, loc, msg, input, ctx}, ...]raise ValueError in a validator becomes value_errorserialization, the other direction: field_serializer, computed_field, model_serializer, then model_dump() / model_dump_json()
     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 / annotationSignatureSeesUse for
@field_validator("f") (after)(cls, value[, info]) classmethodTyped valueBusiness rules on one field
@field_validator("f", mode="before")(cls, value[, info])Raw valueNormalising input
@field_validator("f", mode="wrap")(cls, value, handler[, info])Raw value + handlerFallbacks
@field_validator("f", mode="plain")(cls, value[, info])Raw valueReplacing type rules
AfterValidator(fn) etc. in Annotatedfn(value[, info])Same as aboveReusable across models
@model_validator(mode="before")(cls, data) classmethodRaw inputReshaping input
@model_validator(mode="after")(self) returns selfInstanceCross-field rules
@model_validator(mode="wrap")(cls, data, handler)Raw + handlerLogging, fallback models
info: ValidationInfo.data, .context, .field_name, .modeAlready-validated fields, contextRules 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”".

payment: {"kind": "card", "brand": "amex", "last4": "12"}Field(discriminator="kind")plain Union[Card, BankTransfer, Wallet]read kind = "card"Cardnot triednot tried2 errors: loc ("card", "brand"), ("card", "last4")kind "crypto": 1 error union_tag_invalidone lookup, O(1) in the number of memberssmart mode: try every memberCard: 2Bank: 2Wallet: 26 errors: Card.brand, Card.last4, BankTransfer.kind,BankTransfer.iban, Wallet.kind, Wallet.providercost grows with every memberno tag field? Discriminator(callable) + Annotated[Card, Tag("card")]: the function returns the tag{"last4": "4242"} to Card, {"iban": ...} to BankTransfer, None to union_tag_not_foundJSON Schema: oneOf + discriminator.propertyName "kind" + mapping (OpenAPI clients use it)
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 triedAll, best match winsIn order, first successExactly oneExactly one
Errors on failureEvery member'sEvery member'sThe chosen member'sThe chosen member's
Needs a tag fieldNoNoYes (Literal)No (function decides)
JSON SchemaanyOfanyOfoneOf + discriminator mappingoneOf
SpeedGrows with membersGrows with membersOne lookupOne 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.

py
"""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]]).

NeedUse
Envelope reused for many item typesclass Page(BaseModel, Generic[T])
Top-level JSON array or scalarRootModel[list[X]] or a TypeAdapter
Normalise a list as a whole@field_validator("root") on a RootModel
isinstance on a parametrised modelSubclass 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).

py
"""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 value

Real 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.

NeedTool
Validate a list of models in one callTypeAdapter(list[Model]).validate_json(body)
Validate a TypedDict / dataclass / unionTypeAdapter(T)
JSON Schema of any typeTypeAdapter(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.

py
"""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 True

model_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).

KeyValuesWhen
extra"ignore" / "forbid" / "allow"forbid for input DTOs, allow for pass-through proxies
frozenboolValue objects, cache keys
from_attributesboolOutput DTOs from ORM/domain objects (v1 orm_mode)
validate_by_name (2.11+) / populate_by_nameboolAccept Python names besides aliases
serialize_by_alias (2.11+)boolDump by alias by default
strictboolInternal contracts
validate_assignmentboolMutable models
hide_input_in_errorsboolHides input in the printed error only; errors()/json() still contain input
str_strip_whitespaceboolForm input
use_enum_valuesboolStore .value instead of the member
arbitrary_types_allowedboolFields of classes Pydantic does not know (checked with isinstance only)
regex_engine"rust-regex" / "python-re"Look-arounds needed
defer_buildboolMany 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": false

Real 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 featureJSON 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_generatorProperty names are the aliases (default by_alias=True)
computed_fieldSerialization mode only, "readOnly": true
Custom type with GetPydanticSchemaFrom 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.

py
"""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 True

Custom 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.

py
"""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.

SituationApproach
A rule on an existing typeAnnotated[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 ownAnnotated[Cls, GetPydanticSchema(fn)]
Only isinstance neededarbitrary_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.

py
"""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"] == expected

ValidationError: 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
missingRequired field absent
extra_forbiddenUnknown key with extra="forbid"
int_parsing / int_from_float / int_typeNot an int / float with fraction / strict
bool_parsing / bool_typeNot a recognised bool / strict
string_type / string_too_short / string_too_long / string_pattern_mismatchString rules
too_short / too_longList/set/dict length
greater_than / less_than_equal / multiple_ofNumeric bounds
decimal_max_places / decimal_max_digitsDecimal precision
literal_error / enumValue not allowed
union_tag_invalid / union_tag_not_foundDiscriminated union
model_typeObject given where a dict or instance was expected
datetime_parsing / datetime_from_date_parsing / timezone_awareDate/time rules
json_invalidMalformed JSON in model_validate_json
frozen_instance / frozen_fieldAssignment to frozen model/field
value_error / assertion_errorRaised 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 us

Real 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.

TipGainCost
Reuse TypeAdapter / modelsNo rebuild per call (5x here)None
model_validate_json on bytesNo Python dict in betweenNone
Discriminated unionsOne member validatedA tag field
TypedDict for inner rowsFewer objectsNo methods
Avoid wrap/plain Python validators in hot loopsStay in RustExpress rules as constraints
defer_build=TrueFaster importFirst use pays
FailFast() on long listsStop at first bad itemFewer 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.

py
"""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 way

v1 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 -> PydanticUserError

Real 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 v1Pydantic v2
Model.parse_obj(d)Model.model_validate(d)
Model.parse_raw(s)Model.model_validate_json(s)
Model.from_orm(o) + orm_modeModel.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_namevalidate_by_name (populate_by_name before 2.11)
anystr_strip_whitespacestr_strip_whitespace
GenericModelBaseModel + Generic[T]
__root__RootModel
parse_obj_as, schema_ofTypeAdapter
Field(regex=...), const=Field(pattern=...); Literal
BaseSettings in pydanticpydantic-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).

py
"""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 = True

pydantic-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('**********')).

py
"""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 JSON

Real 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.

OptionExampleEffect
env_prefix"SHOP_"SHOP_DEBUG → debug
env_nested_delimiter"__"SHOP_DB__POOL_SIZE → db.pool_size
env_file".env" or a tuple of filesdotenv source; later files win
env_file_encoding"utf-8"
secrets_dir"/run/secrets"One file per field, file name = env name
case_sensitiveFalse (default)Names matched case-insensitively
extra"forbid" (default)Unknown dotenv keys fail; set "ignore" for shared .env files
SecretStr / SecretBytespayment_api_key: SecretStrMasked 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.

py
"""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.

Pydantic at the edges, plain objects in the middleJSON requestcamelCaseOrderIn (DTO)aliases, extra="forbid"validatorsOrder (domain)dataclass, pay(), totalno wire formatOrderOut (DTO)from_attributescomputed_fieldJSONby_aliasSQLAlchemy / SQLModel rowor JSON column (model_dump_json)Settings(BaseSettings) at startupenv, .env, secrets_dir; fails fastinvalid input: ValidationErrorFastAPI turns it into 422before any of this runs: mypy / pyright read the same annotations statically(Protocol, NewType, Literal, Final, overload are checked here, never at runtime)
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 DTODomain objectOutput DTOTable model
LibraryPydanticdataclass / attrs / plain classPydanticSQLAlchemy 2 / SQLModel
Knows aliases, JSONYesNoYesNo (columns)
ValidatesUntrusted inputInvariants in methodsOutput shapeDatabase constraints
Has behaviourNoYesComputed fields onlyRelationships
Changes whenAPI changesBusiness rules changeAPI changesSchema 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.

py
"""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)]
py
"""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 data

How 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"]).

StageWhenFailure you see
Annotation resolutionClass creationIncomplete model, PydanticUserError at first use
Schema generationClass creation (or first use with defer_build)PydanticSchemaGenerationError for unknown types (fix: core schema or arbitrary_types_allowed)
Core schema compileClass creationSchemaError (e.g. a regex the Rust engine rejects)
ValidationEvery callValidationError
SerialisationEvery dumpPydanticSerializationError 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.

TriggerExact 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=1List 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 kindInput 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_attributesInput should be a valid dictionary or instance of OrderOut [type=model_type]
Assignment to a frozen modeltype=frozen_instance
Field type imported under TYPE_CHECKINGPydanticUserError: `Invoice` is not fully defined; you should define `Money`, then call `Invoice.model_rebuild()`.
typing.TypedDict on 3.9PydanticUserError: Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.
TypeAdapter(int | None) on 3.9TypeError: 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 = TrueSupport for class-based `config` is deprecated, use ConfigDict instead. + * 'orm_mode' has been renamed to 'from_attributes'
a: Final = 1 in a modelPydanticDeprecatedSince211: 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 secretloc ("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 import422 {"detail":[{"type":"missing","loc":["query","amount"],"msg":"Field required","input":null}]}; /openapi.json → 500
mypy on static_errors.pyerror: 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.

sql
-- 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 ​

BugSymptomFixCost
Dicts passed around untypedKeyError deep in the code; mypy silent (Any)Model at the boundaryOne class
First error onlyClients fix one field per round tripPydantic collects all errorsNone
Unknown keys acceptedisAdmin: true stored or acted onextra="forbid" on input DTOsClients must send clean payloads
Float money0.1 + 0.2 cents lostDecimal + decimal_places=2 + string serialiserNone
Naive datetimesTimes shift by the server's zoneRequire an offset (AwareDatetime or an after validator), dump UTCNone
Plain union of modelsWrong model picked, six errors for one problemDiscriminated unionA Literal tag
Alias config on parent onlyField required on nested fieldsShared base classNone
TypeAdapter in a function5x slower validationModule-level adapterNone
Optional[X] without default"Optional" field is required= NoneNone
Mutable class-level defaultPlain 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 importIncomplete model, or FastAPI query param + 422Real import, Ruff runtime-evaluated-base-classesImport cost
Same model for input and outputClients can set id; responses leak fieldsSeparate In/Out DTOsTwo classes
Secrets in repr and logsAPI keys in error trackersSecretStr; hide_input_in_errors for printed errors plus errors(include_input=False) wherever errors are logged or returned.get_secret_value() calls
Settings read lazilyCrash at first use in productionSettings() at startup, required fieldsNone
v1 calls left behindDeprecation warnings, v3 breakage laterbump-pydantic, warnings as errors in CIOne 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 ​

SituationUseExtra techniqueReason
HTTP request/response bodiesPydantic BaseModel (via FastAPI)extra="forbid" on input, from_attributes on outputValidation + OpenAPI
Queue / webhook payloadsBaseModel + model_validate_jsonDiscriminated union on typeOne parse, clear errors
Domain entities with rules@dataclass (or attrs)Conversion functions from DTOsNo wire coupling
Small immutable values@dataclass(frozen=True) or frozen modelMoney as a frozen model if it crosses the wireHashable, safe
Dict-shaped data, high volumeTypedDict + TypeAdaptertyping_extensions.TypedDict on < 3.12Faster than nested models
Top-level JSON arraysTypeAdapter(list[X])Module-levelNo wrapper model
Function arguments from untrusted callers@validate_callstrict=True for internal APIsBoundary without HTTP
Configurationpydantic-settings BaseSettingsSecretStr, secrets_dirFail fast, typed
Internal service contractsPydantic in strict modeShared models package, versionedProducer bugs surface
Plug-in points / test doublesProtocolSmall, consumer-ownedStructural, no inheritance
Ids that must not mixNewTypemypy/pyright in CIFree at runtime
Static checkingmypy (strict, Pydantic plugin) or pyrightBoth in CI on new codeCatch bugs before running

When Pydantic vs dataclasses, attrs or TypedDict ​

NeedPydantic v2dataclassesattrsTypedDict
Validate untrusted inputYes (lax or strict)NoOpt-in validatorsOnly through Pydantic
Parse JSON directlymodel_validate_jsonNoVia cattrsVia TypeAdapter
JSON Schema / OpenAPIYesVia PydanticNoVia Pydantic
Aliases, camelCaseYesNoNoNo
Zero dependenciesNo (pydantic, pydantic-core)Yes (stdlib)No (one package)Yes
Per-instance costValidation every timeLowestLowNone (a dict)
FastAPI integrationNativeWorks (converted)NoAs 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× ​

LoadWhat changesTyping and Pydantic practice
1× (one process)Correctness is the problemModels at every boundary, mypy in CI, separate In/Out DTOs, required settings
10× (several workers or services)Contracts between teams, rolling deploysVersioned 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 driftReuse 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.07s

These 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})
True

Then 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().

php
// 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 / PHPPython typing / Pydantic
Form Request rules()BaseModel fields + Field constraints
prepareForValidation()@model_validator(mode="before")
after() hook@model_validator(mode="after")
Custom rule classAfterValidator / 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 errorsValidationError → FastAPI 422 detail list
Laravel casts: boolean, integer, decimal:2, datetime, arrayField types with lax coercion
encrypted castSecretStr (masking, not encryption)
$hidden on a modelField(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.

go
// 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
}
ConcernPython + Pydantic v2Go
Static typesAnnotations + mypy/pyright (optional)Compiler (mandatory)
Runtime validationPydantic (built from annotations)go-playground/validator (struct tags)
Wire namesalias, alias_generator=to_cameljson:"customerEmail" per field
Unknown keysextra="ignore" default, "forbid"Ignored by default, DisallowUnknownFields()
"2" into an intAccepted in lax mode*json.UnmarshalTypeError
OptionalX | None = NonePointer or omitempty / omitzero
Tagged unionsField(discriminator=...)Interface + Kind field + type switch
Structural typingProtocolInterfaces (implicit)
ErrorsValidationError.errors()validator.ValidationErrors, FieldError
JSON Schemamodel_json_schema()Third-party generators
Configpydantic-settingsos.Getenv / envconfig-style libraries

Common misconceptions ​

BeliefReality
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 validIt checks code consistency; Any from json.loads is unchecked; runtime data needs validation
Optional[X] means the field can be omittedIt means the value can be None; only a default makes it omittable
from __future__ import annotations is harmlessRuntime readers must resolve strings; TYPE_CHECKING imports and local classes break Pydantic and FastAPI
X | None works everywhere on 3.9Only inside postponed annotations; as an expression it raises TypeError
NewType and Final do something at runtimeBoth are static-only; UserId(5) is the int 5
@runtime_checkable checks method signaturesIt checks that the names exist
A dataclass validates its fieldsNothing in @dataclass examines the annotated types
Pydantic validates the inputIt guarantees the output; lax mode converts "3" to 3
Lax mode converts anything3.5 → int, "1e3" → int, numbers → str all fail
Strict mode rejects strings for dates everywhereJSON input still accepts ISO strings for datetime, Decimal, UUID
model_dump() is JSON-readymode="python" keeps Decimal, datetime, custom objects; use mode="json"
exclude_unset and exclude_none are the sameUnset = never provided; none = provided or defaulted to None
Unknown keys are rejected by defaultextra="ignore" on BaseModel; "forbid" is opt-in (BaseSettings defaults to "forbid")
Nested models inherit the parent's configmodel_config is per class; use a shared base
Assignment is validatedOnly with validate_assignment=True; model_copy(update=...) is never validated
A plain Union picks the right modelSmart 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 typesLax mode converts them; add strict=True
Creating a TypeAdapter is freeIt builds a validator each time; reuse one
Field(pattern=...) is Python reRust regex by default: no look-arounds
extra="forbid" on settings catches typoed variablesUnmatched environment variables are ignored
v1 code that still runs is migratedDeprecated calls warn, and coercion defaults changed underneath

Cheat sheet ​

TopicRemember
HintsMetadata; mypy/pyright check statically, Pydantic at runtime
OptionalX | None = None (default makes it optional); 3.9: Optional[X] in runtime expressions
Future importStrings everywhere; real imports for runtime-read types; deprecated in 3.14
Literal / EnumClosed sets; Pydantic validates both
ProtocolStructural, consumer-owned, small
GenericsGeneric[T] / class Page[T] (3.12); ParamSpec in decorators; Self for builders
AnnotatedAnnotated[int, Field(gt=0)]; before/wrap right to left, after left to right
Modelclass X(BaseModel); validated on construction only
Validatemodel_validate(obj), model_validate_json(bytes); model_construct = no checks
Dumpmodel_dump(mode="json", by_alias=True, exclude_unset=True), model_dump_json()
Lax/strictLax default; strict per call/field/model; JSON keeps string dates in strict
AliasesShared base with alias_generator=to_camel + validate_by_name; AliasChoices for migrations
Fieldgt ge lt le, min_length max_length, pattern, max_digits, decimal_places, default_factory
Validatorsafter (typed) > before (reshape) > wrap (rare) > plain (replace); model after for cross-field
UnionsField(discriminator="kind") + Literal tags; callable Discriminator + Tag for legacy
Configextra="forbid" in, from_attributes out, frozen for values
ErrorsBranch on type; loc uses input names; errors(include_input=False) for secrets (hide_input_in_errors covers printing only)
PerformanceReuse adapters, validate JSON bytes directly, tagged unions, TypedDict for bulk
Migrationmodel_ prefixes, field_validator/model_validator, ConfigDict, bump-pydantic
Settingsinit > env > .env > secrets dir > defaults; SecretStr; fail at startup
ArchitectureDTOs at the edges, plain domain objects inside

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Type hintsAnnotations on names (x: int, -> str) that Python stores but does not enforce
Gradual typingAdding annotations incrementally; unannotated code is treated as Any
mypyStatic type checker; skips unannotated functions unless --check-untyped-defs; Pydantic plugin pydantic.mypy
pyrightMicrosoft's static type checker (its configuration docs also cover Pylance); checks unannotated code by default
AnyThe 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 | NonePEP 604 spelling of Optional[X]; a runtime TypeError on 3.9 outside postponed annotations
from __future__ import annotationsPEP 563: store annotations as strings; deprecated in 3.14 (deferred evaluation, PEP 649/749)
TYPE_CHECKINGConstant that is True only for type checkers; imports under it do not exist at runtime
LiteralType of exact values (PEP 586); validated by Pydantic (literal_error)
TypedDictShape of a dict (PEP 589); a plain dict at runtime; use typing_extensions for Pydantic on < 3.12
NotRequiredTypedDict key that may be absent (PEP 655, 3.11)
ProtocolStructural interface (PEP 544)
Structural subtypingCompatibility by shape (methods/attributes), not by inheritance
Generic / TypeVarType parameters for classes and functions
ParamSpecType variable for a callable's parameter list (PEP 612)
NewTypeDistinct static type over an existing runtime type
FinalName that must not be reassigned (PEP 591); static only
overloadSeveral static signatures for one runtime function
Self"An instance of the current class" (PEP 673, 3.11)
TypeAliasExplicit alias annotation (PEP 613, 3.10)
type statementtype X = ... (PEP 695, 3.12): lazily evaluated TypeAliasType
AnnotatedAnnotated[T, *metadata] (PEP 593): type plus metadata for runtime tools
dataclassStdlib decorator generating __init__/__repr__/__eq__; no type checks
NamedTupleTuple subclass with named fields
attrsThird-party class builder with opt-in validators and converters
Pydantic v2Validation and serialisation library driven by type hints, core in Rust
pydantic-coreRust engine of Pydantic v2 (validator + serializer); now in the main pydantic repository
RustLanguage of pydantic-core; validation for most types runs there
jiterThe JSON parser used by Pydantic
BaseModelBase class for Pydantic models
Core schemaPydantic's internal description of a type, compiled by pydantic-core
lax modeDefault validation mode: converts well-defined representations
strict modeOnly exact types (JSON exceptions for dates, decimals, UUIDs, tuples)
coercionConverting input to the field type ("3" → 3)
conversion tableThe docs' per-type list of accepted inputs in lax/strict, Python/JSON
model_validateValidate a Python object into a model
model_validate_jsonParse and validate JSON in one Rust pass
model_constructCreate without validation
model_dumpModel to dict (mode="python" or "json")
model_dump_jsonModel to JSON text
exclude_unsetDump only fields that were provided
exclude_noneDump without None values
by_aliasDump using aliases
aliasField name on the wire, both directions
validation_aliasInput-only name(s); AliasChoices, AliasPath
serialization_aliasOutput-only name
alias_generatorFunction generating aliases for every field
to_camelpydantic.alias_generators.to_camel: customer_email → customerEmail
populate_by_name / validate_by_nameAccept Python names besides aliases (validate_by_name since 2.11)
FieldPer-field defaults, constraints, aliases, docs
constraints gt ge lt leNumeric bounds in Field/Annotated
min_length max_lengthLength bounds for strings and collections
patternRegex for strings (rust-regex by default)
default_factoryCallable producing a fresh default
computed_fieldProperty included in serialisation and the serialization schema
field_validatorValidator for one or more fields; modes before/after/wrap/plain
model_validatorValidator for the whole model; modes before/after/wrap
mode before after wrapWhen a validator runs relative to the core check
AfterValidator / BeforeValidator / WrapValidator / PlainValidatorThe same modes as reusable Annotated metadata
field_serializer / model_serializerCustom serialisation of a field / the whole model
discriminated unionUnion selected by a tag field (Field(discriminator=...))
Discriminator / TagCallable discriminator and member labels
generic modelsBaseModel subclasses with type parameters (Page[T])
RootModelModel whose value is a single non-dict value (.root)
TypeAdapterValidation, serialisation and schema for any type
validate_callDecorator validating function arguments (and optionally the return)
model_config / ConfigDictPer-model configuration
extra forbid ignore allowWhat happens to unknown keys
frozenFaux-immutable: no attribute assignment, __hash__ generated (works only if all field values are hashable); nested mutable values can still change
from_attributesRead objects by attribute (v1 orm_mode)
JSON SchemaStandard description of JSON data; model_json_schema() (Draft 2020-12)
custom typesTypes Pydantic learns through a core schema
GetPydanticSchemaAnnotated helper supplying a core schema for a foreign type
ValidationErrorException carrying all validation errors
errors()List of error dicts with loc type msg input (plus ctx, url)
error typesStable codes such as missing, int_parsing, extra_forbidden
performanceRust validation is cheap; schema building, Python callbacks and dict round trips are not
defer_buildBuild validator/serializer on first use
v1 to v2 migrationRenamed methods, new validators and config, changed coercions; bump-pydantic
parse_obj deprecatedv1 method; use model_validate
pydantic-settingsPackage with BaseSettings for typed configuration
BaseSettings / SettingsConfigDictSettings model and its config
env_prefixPrefix for environment variable names
env_nested_delimiterSeparator mapping env names onto nested fields
secrets_dirDirectory of one-file-per-secret values
dotenv.env file source, below environment variables in priority
SecretStrString masked in repr; .get_secret_value() reads it
DTOData transfer object: the shape of data at a boundary
Domain objectObject holding business rules and invariants
DTO vs domain objectPydantic at the edges, plain classes in the core
Go struct tagsjson:"name,omitempty" / validate:"gt=0" strings on Go struct fields
go-playground validatorGo library validating structs from validate tags
Laravel Form RequestRequest class with rules(), authorize(), prepareForValidation()
Laravel castsEloquent casts() converting attributes to types
FastAPI / Starlette / UvicornThe web framework built on Pydantic, its ASGI toolkit, and the server
SQLAlchemy / SQLModel / AlembicORM, Pydantic-based ORM models, and migrations
pytest / httpxTest runner used by the snippets; HTTP client used by FastAPI's TestClient

References ​

Built by Morteza Negahi