Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Settings and Config

ConfigDict: Model Configuration Options

Change how a Pydantic model behaves with ConfigDict. Learn extra, frozen, strict, validate_assignment, str_strip_whitespace, alias_generator and from_attributes.

A Pydantic model has default behavior: it ignores unknown keys, converts compatible types, lets you assign anything after creation and uses field names as input keys. Every one of those defaults can be changed with the model_config class attribute, which holds a ConfigDict. Configuration is how you turn a flexible model into a strict API contract, an immutable value object or a model that reads from database rows.

This lesson walks through the options you will use most. Each one is a small switch with one clear effect.

Python
from pydantic import BaseModel, ConfigDict

class User(BaseModel):
    model_config = ConfigDict(extra="forbid", frozen=True)
    name: str

Configuration is inherited: a subclass gets its parent's settings and can override single keys, so a common base class is a good place for project-wide rules.

extra: unknown keys

The extra option decides what happens to input keys that are not fields. There are three choices: "ignore" (the default) drops them, "forbid" raises an error, and "allow" keeps them as extra attributes.

Python extra: ignore, forbid, allow

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.

Use forbid on models that receive client input, so a misspelled or malicious key is noticed. Use allow rarely, for pass-through data.

frozen: immutable models

With frozen=True, assigning to a field after creation raises an error, and the model gains a __hash__, so instances can be dictionary keys or set members. It suits value objects such as coordinates or money amounts.

Python Frozen models are hashable

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.

validate_assignment: check changes too

By default Pydantic validates only when the object is created. Later user.age = "oops" silently stores bad data. validate_assignment=True runs validation on every assignment, including type coercion.

Python validate_assignment

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.

Assignment validation costs a little time per assignment, so enable it where objects are mutated after creation and bad state would be harmful.

strict: no coercion

Pydantic's default mode is lax: "42" becomes 42 and 1 becomes True. With strict=True a value must already have the declared type. It is a good choice when your data comes from code you control and a string in an integer field would be a bug, not a convenience.

Python Lax and strict mode

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.

JSON input is a special case: in strict mode model_validate_json still accepts the JSON types that map cleanly to Python ones. You can also make a single field strict with Field(strict=True) or the StrictInt family of types.

Cleaning text: str_strip_whitespace and friends

String options tidy text before any other check, so a name of " Ada " passes a min_length check on the cleaned text. Useful ones are str_strip_whitespace, str_to_lower, str_to_upper, str_min_length and str_max_length.

Python String options

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.

Aliases: different names on the wire

External data often uses different naming: firstName in JSON, first_name in Python. An alias is the external name. alias_generator creates one for every field. Pydantic ships to_camel, to_pascal and to_snake in pydantic.alias_generators.

With an alias set, input must use the alias by default. The option validate_by_name=True lets callers use the Python name too (and validate_by_alias controls the alias itself). When you serialize, pass by_alias=True to get the external names back.

Python alias_generator and by_alias

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.

Aliases and the three serialization names are covered in depth in the serialization chapter of this track. Here you only need to know where the switches live.

from_attributes: reading objects

Normally model_validate takes a dictionary. With from_attributes=True it can also read attributes from any object: an ORM row, a dataclass or a plain class. This is how you turn a database object into an API model.

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

The private password_hash never reaches the output model, because the output model does not declare it.

A few more options

Option Effect
use_enum_values Store the enum's value instead of the enum member.
revalidate_instances Validate again when an existing model instance is passed in (never by default).
arbitrary_types_allowed Allow field types Pydantic does not know, checked with isinstance.
title, json_schema_extra Adjust the generated JSON Schema.
protected_namespaces Warn when a field name starts with a reserved prefix such as model_.
populate_by_name Older spelling of letting callers use the field name beside an alias.

Model-level options set the default for every field. A single field can override them with Field(...), and a call such as model_validate(data, strict=True) can override them for one call.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which setting makes a model reject input keys that are not declared as fields?

    extra="forbid" turns unknown keys into validation errors. "ignore" (the default) drops them and "allow" stores them.
  2. 2. What is the effect of frozen=True?

    Assignment raises a ValidationError, and the model gets a hash based on its field values.
  3. 3. A model has only default settings. What happens on user.age = "abc" after the user was created?

    Without validate_assignment=True, validation runs only when the model is created.
  4. 4. What does from_attributes=True allow?

    It lets model_validate accept ORM rows, dataclasses and other objects, not only dictionaries.

Summary

  • model_config = ConfigDict(...) changes a model's behavior; subclasses inherit it.
  • extra controls unknown keys; use forbid for client input.
  • frozen gives immutability and hashing; validate_assignment checks changes after creation.
  • strict turns off coercion; string options clean text before other checks.
  • alias_generator with validate_by_name maps external names; from_attributes reads objects.

Next: Secrets and Settings Patterns