In Pydantic 2, how do you turn on strict mode for a whole model, for one field, or for a single validation call?
answer
- three scopes, one switch
- model_config versus Field
- a keyword on model_validate
- nested models keep their own config
basics
~10 sPydantic 2 offers three scopes: ConfigDict(strict=True) for a model, Field(strict=True) or StrictInt-style types for one field, and strict=True on model_validate or a TypeAdapter method for one call.
solid answer
~40 sFor a whole model, set `model_config = ConfigDict(strict=True)`; subclasses inherit it, but nested models do not, because each model is its own configuration boundary. For one field, use `Field(strict=True)`, `Annotated[int, Strict()]` or an alias such as `StrictInt` or `StrictBool`; a strict field stays strict even when the call is lax, and `Field(strict=False)` relaxes one field inside a strict model. For one call, pass `strict=True` to `model_validate`, `model_validate_json` or a `TypeAdapter`'s `validate_python` and `validate_json`; the plain constructor takes no such argument. Strict then means only instances of the declared type pass, so `'500'` for an `int` fails with `int_type`, with documented exceptions for JSON input such as date strings.
code
python · 33 linesfrom pydantic import BaseModel, ConfigDict, Field, StrictBool, ValidationError
class Refund(BaseModel):
model_config = ConfigDict(strict=True)
amount_cents: int
reason_code: int = Field(strict=False)
print(Refund(amount_cents=500, reason_code='7'))
#> amount_cents=500 reason_code=7
try:
Refund(amount_cents='500', reason_code=7)
except ValidationError as exc:
print(exc.errors()[0]['type'])
#> int_type
class Charge(BaseModel):
amount_cents: int
captured: StrictBool
print(Charge.model_validate({'amount_cents': '900', 'captured': True}))
#> amount_cents=900 captured=True
try:
Charge.model_validate({'amount_cents': '900', 'captured': True}, strict=True)
except ValidationError as exc:
print(exc.errors()[0]['type'])
#> int_typego deeper
Recall the three places strict mode lives: ConfigDict(strict=True) on the model, Field(strict=True) or StrictInt on a field, strict=True on model_validate.
Explain how scopes interact: a field override inside a strict model, a strict field inside a lax call, and why the constructor cannot take strict.
Show you know the traps: nested models keep their own config, strict float still takes int, and JSON input relaxes strictness for dates and UUIDs.
Pick the scope as a policy tool: field-level for risky fields, a strict base model for owned contracts, call-level to measure before committing.
## Three scopes for one switch **Strict mode** in Pydantic 2 tells the validator to stop converting: an input must already be of the declared type, with a few documented exceptions for JSON input. It can be enabled at three scopes, and real codebases use all three. | Scope | How you write it | What it covers | |---|---|---| | Model | `model_config = ConfigDict(strict=True)` | every field of the model and of its subclasses | | Field | `Field(strict=True)`, `Annotated[int, Strict()]`, `StrictInt`, `StrictBool` | one field, even when the call is lax | | Call | `model_validate(data, strict=True)`, `TypeAdapter(T).validate_python(data, strict=True)` | that one validation | ## Model level `model_config = ConfigDict(strict=True)` makes every field of that model strict. Two rules about its reach matter in practice: - **Subclasses inherit it.** A subclass's own `model_config` is merged with its parent's, so a shared base model can carry `strict=True` for a family of models. - **Nested models do not.** Pydantic documents each model as its own configuration boundary: configuration is not propagated into a field typed as another `BaseModel`. A strict `PaymentBatch` whose `items: list[LineItem]` uses a lax `LineItem` still converts `'500'` inside each item. Inside a strict model, `Field(strict=False)` relaxes one field, which is the documented way to carve out a deliberate exception. ## Field level There are three spellings of the same idea: - `Field(strict=True)` on the field, or `Annotated[int, Field(strict=True)]`; - the `Strict()` metadata class in the annotated pattern: `Annotated[UUID, Strict()]`; - convenience aliases: `StrictBool`, `StrictInt`, `StrictFloat`, `StrictStr` and `StrictBytes`, where `StrictInt` is equivalent to `Annotated[int, Strict()]`. The documentation states that a strict field stays strict even when the validation method is called in lax mode. Because the annotated pattern is just a type, a team can name it once, for example `Cents = Annotated[int, Strict()]`, and reuse it across every payment model, which keeps the rule in one place. Field-level strictness is the precise tool: a `captured: StrictBool` flag can refuse `'yes'` while the rest of the event model keeps accepting `'1250'` for a count. ## Call level The validation methods take a `strict` keyword: `model_validate`, `model_validate_json` and `model_validate_strings` on models, and `validate_python`, `validate_json` and `validate_strings` on a `TypeAdapter`. Passing `strict=True` validates that one input strictly without changing the model. The **constructor** (`PaymentEvent(**data)`) takes only field values, so it has no such parameter; the documentation contrasts it with the `model_validate_*()` methods, which let you control strictness, extra data and validation context. ## What strict actually refuses Strict mode is not "no conversions anywhere"; it follows the strict column of the conversion table: - `int` accepts only `int`, and `bool` is explicitly forbidden, so `True` fails; - `bool` accepts only `True` and `False`; - `str` accepts only `str`; - `float` still accepts an `int`, because inputs with `__float__()` or `__index__()` are valid; - `date`, `UUID` and `Decimal` accept only instances from Python input, but JSON strings in JSON mode, because JSON has no such types. A refused value raises an error such as **`int_type`** ("Input should be a valid integer") rather than a parsing error. ## Strict mode and JSON input The documentation states that strict mode is looser when validating from JSON. `TypeAdapter(date).validate_python('2000-01-01', strict=True)` fails with `date_type`, while `TypeAdapter(date).validate_json('"2000-01-01"', strict=True)` returns a `date`, because JSON has no date type and a string is the only way to send one. `UUID` and `Decimal` strings behave the same way. Types JSON can express natively stay strict: a JSON string `"500"` is still refused for an `int`. So the same strict model can behave differently depending on whether you call `model_validate` or `model_validate_json`, which is worth knowing before you choose a scope. ## Choosing a scope 1. **Call level** for a one-off check: auditing a batch, or measuring what strict mode would reject before you adopt it. 2. **Field level** for the handful of fields where conversion hides bugs: flags, money, identifiers. 3. **Model level** for a contract between services you own, with `Field(strict=False)` for each documented exception and a strict base model so nested models do not slip back to lax. Interviewers often follow up on the nested-model rule, because "I set strict on the model" is where many teams believe they are protected and are not.
- In Pydantic 2, why does a strict outer model still accept '500' inside a nested item model?Configuration is not propagated into nested models: each `BaseModel` is its own configuration boundary. The nested item model keeps its own lax config. Give it `ConfigDict(strict=True)` too, or have both inherit from a strict base model, whose config subclasses merge.
- Does strict mode in Pydantic 2 refuse an int for a float field?No. The strict column still lets a `float` field accept an `int`, because inputs with `__float__()` or `__index__()` are valid in strict mode. What strict `float` refuses is a numeric string such as `'3.5'` and a `bool`.
- Setting ConfigDict(strict=True) on an outer model makes its nested models strict too.
- You can pass strict=True to the model constructor like any field value.
- Strict mode refuses every conversion, so a float field rejects the int 3.
- A model with strict config cannot relax any single field.
- StrictInt is a Pydantic 1 relic that Pydantic 2 removed.