Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

How Pydantic Validation Works

Understand what Pydantic does when it validates input: conversion rules, lax versus strict mode, extra keys, field order, and why models validate on creation.

You now know how to create a model. This lesson looks at what Pydantic actually does with your input, because a clear mental model prevents most surprises. You will learn the default conversion rules, how extra keys are handled, and the order in which fields are processed.

Validation means parsing

When you call Model(...) or Model.model_validate(...), Pydantic walks over the declared fields and, for each one, takes the input value and tries to produce a value of the declared type. Three outcomes are possible:

  1. The input already has the right type: it is kept as it is.
  2. The input can be safely converted: the converted value is stored. "42" becomes 42.
  3. The input cannot be converted: an error is recorded for that field.

If any field recorded an error, a ValidationError is raised after all fields have been tried.

flowchart TD
    A["For each field"] --> B{"Right type<br/>already?"}
    B -->|yes| E["Keep value"]
    B -->|no| C{"Safe conversion<br/>possible?"}
    C -->|yes| D["Store converted value"]
    C -->|no| F["Record error"]
    E --> G["Next field"]
    D --> G
    F --> G
    G --> H{"Any errors?"}
    H -->|no| I["Return model"]
    H -->|yes| J["Raise ValidationError"]

Every field is tried; errors are collected, not thrown one by one.

Default conversions (lax mode)

The default mode is called lax. It accepts reasonable conversions. A few examples for common types:

Python What lax mode accepts

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.

Key facts about lax mode:

  • int: accepts 7, "7", and 7.0 (a float with no fractional part). It rejects 7.5.
  • float: accepts ints and numeric strings.
  • bool: accepts True/False, the ints 0 and 1, and strings such as "true", "false", "yes", "no", "on", "off", "1", "0", "t", "f", "y", "n".
  • str: accepts only strings (and bytes). A number is not turned into text automatically. This avoids hiding bugs.

The Strict Mode and Coercion lesson shows how to switch conversions off, and the whole table of conversions is in the Pydantic documentation. You will rarely need to memorize it: try a value and see.

Extra keys

What happens when the input has keys the model does not declare? By default they are ignored and dropped:

Python Extra data is ignored by default

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.

The extra setting has three values:

Value Behaviour
"ignore" (default) unknown keys are silently dropped
"forbid" unknown keys raise an error: good for APIs where a typo should be loud
"allow" unknown keys are kept and available as attributes and in model_extra

Order and defaults

Fields are validated in the order they are declared. A field with a default is not validated when it is not provided: the default is trusted. This is a performance feature, and it is why a wrong default such as age: int = "old" is not noticed until you ask for validation of defaults with validate_default=True.

Python Defaults are not validated

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.

Models validate when created, not while you use them

A model instance is checked when it is built. After that, it is a regular Python object, and Pydantic does not watch it. This has one important consequence: trust the model, not the raw data. Convert input to a model at the edge of your program (a request handler, a file reader), and let the rest of your code work with typed objects.

Nested data works the same way: a model that contains another model validates the inner data too. Nested models are covered in the next chapter.

Validating objects, not only dicts

model_validate also accepts objects with attributes, if you set from_attributes=True. This is handy for ORM rows and other objects:

Python Validating from attributes

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the default lax mode, what happens to Model(count='7') when count is an int field?

    Lax mode converts numeric strings to ints when the conversion is safe.
  2. 2. An int field receives 7.5. What does Pydantic do?

    Floats are accepted for int fields only when they have no fractional part (7.0). 7.5 is rejected.
  3. 3. How are unknown input keys treated by default?

    The default is extra='ignore'. Use 'forbid' to raise errors or 'allow' to keep them.
  4. 4. A field has the default value 'old' but is declared as int. When is the default checked?

    Defaults are trusted and skipped for speed. Set validate_default=True on the field to check them.

Summary

  • Validation parses each field: keep the value, convert it safely, or record an error. All errors are raised together.
  • Lax mode converts sensible inputs (numeric strings, whole floats, bool words) but does not turn numbers into strings.
  • extra controls unknown keys: ignore (default), forbid, or allow.
  • Defaults are trusted and not validated unless validate_default=True.
  • Validate at the edges of your program, then pass typed models around; use from_attributes=True to read objects.

Next: Model Methods: Dump, Copy and Fields