Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Validation and Constraints

Strict Mode and Coercion

Control how much Pydantic converts input. Compare lax and strict mode, enable strict per field, per model, per call or with StrictInt, and learn the JSON exception.

By default Pydantic is forgiving: it converts "42" to 42, 1 to True, and a timestamp to a datetime. That is perfect for data from forms, query strings and environment variables, where everything starts as text. But sometimes forgiveness hides bugs. If a function receives the string "42" where your own code should have produced an integer, you may want an error. Strict mode switches conversion off.

Lax and strict side by side

Python The same input in both modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In strict mode the value must already have the right Python type. A string is not an int, and 1 is not a bool, even though lax mode would accept both.

Four ways to turn strict mode on

The scope is up to you, from the whole model down to one call.

Python Strict at different scopes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notes:

  • A field with strict=False explicitly overrides a strict model: Field(strict=False) is lax even inside a strict=True model.
  • The strict types are StrictInt, StrictFloat, StrictStr, StrictBytes and StrictBool.
  • Passing strict=True to model_validate is handy in tests and in internal code paths where input must already be typed.

What strict mode still accepts

Strict does not mean "only exact Python types are allowed" in every case. Some points to remember:

Type Strict mode accepts
int an int (not bool, not str, not float)
float a float or an int
bool True or False only
str a str only
datetime a datetime instance only (in Python mode)
list a list only (not a tuple, not a set)

An int is accepted for a float field because it is a lossless widening. Everything else must match the declared type exactly.

The JSON exception

JSON has no dates, UUIDs, tuples or sets, so a JSON document can only express them as strings or arrays. For that reason strict mode relaxes these conversions when you validate JSON (model_validate_json): a date string is accepted for a date field, and an array for a tuple. What strict mode still refuses in JSON are conversions between JSON primitives, such as "1" for an int.

Python Strict mode with JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When to choose which

flowchart TD
    Q["Where does the data come from?"] --> T{"Text-based source?<br/>forms, env vars, query strings, CSV"}
    T -->|yes| L["Lax mode<br/>conversion is helpful"]
    T -->|no| S{"Typed source?<br/>your own code, trusted APIs"}
    S -->|yes| K["Strict mode<br/>catch type bugs early"]
    S -->|unsure| L

Lax for text, strict when types are already meaningful.

A practical rule: configuration and request input are usually lax; internal data between your own services and functions can be strict so that a wrong type shows up immediately instead of being silently converted. Another valid choice: keep a lax model by default and make just the sensitive fields strict, like an id: StrictInt that must never be a string.

bool fields in lax mode accept strings like "no", "off" and "0" as False, and anything unrecognized as an error. If you read flags from user text, that is helpful. If you read flags from an API where "false" should never appear, make the field StrictBool.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A model has strict=True. What happens with Model(n='7') for n: int?

    Strict mode requires the value to already be an int.
  2. 2. Which is NOT a way to enable strict validation?

    There is no coerce argument. Use strict in a field, in the model config, or in the validation call, or a Strict* type.
  3. 3. Why does a strict model accept the date string '2030-01-05' when validating JSON but not when validating a Python dict?

    Strict mode allows the natural JSON representations of types that JSON cannot express directly, like dates, tuples and sets.
  4. 4. In strict mode, which input is accepted for a float field?

    An int can be widened to a float without loss, so it is accepted. Strings are not.

Summary

  • Lax mode (default) converts sensible input; strict mode requires the exact type.
  • Enable strict mode per field (Field(strict=True) or StrictInt), per model (ConfigDict(strict=True)), or per call (strict=True).
  • A field-level strict=False overrides a strict model.
  • When validating JSON, strict mode still accepts JSON's natural forms for dates, UUIDs, tuples and sets.
  • Use lax for text-based sources and strict for typed internal data.

Next: Validating Special Types