Skip to main content

Core Configuration

Core configuration in this codebase is managed through the ConfigDict type, which provides a unified way to control the behavior of validation, serialization, and JSON schema generation. While Pydantic V1 used a nested Config class, this version uses the model_config class attribute or the @with_config decorator to apply settings.

The ConfigDict Type​

Defined in pydantic/config.py, ConfigDict is a TypedDict that specifies all available configuration options. Because it is a TypedDict, it provides full type-hinting and autocompletion in IDEs.

Key configuration categories include:

Validation Settings​

These settings govern how data is parsed and validated into models:

  • strict: When True, Pydantic raises an error instead of attempting to coerce types (e.g., it won't convert the string "123" to an integer 123).
  • extra: Controls how extra fields in the input data are handled. Options are 'ignore' (default), 'allow' (stored in __pydantic_extra__), and 'forbid' (raises a ValidationError).
  • str_to_lower / str_to_upper: Automatically converts strings to the specified case during validation.
  • validate_assignment: When True, re-validates the data whenever an attribute on a model instance is changed.
  • protected_namespaces: A tuple of prefixes or regexes that prevent field names from conflicting with internal model methods. The default is ('model_validate', 'model_dump').

Serialization Settings​

These settings control how models are converted back to dictionaries or JSON:

  • ser_json_temporal: Determines the format for datetime, date, time, and timedelta during JSON serialization. Options include 'iso8601' (default), 'seconds', and 'milliseconds'.
  • serialize_by_alias: When True, uses field aliases instead of attribute names by default when calling model_dump().
  • ser_json_bytes: Controls how bytes are encoded in JSON (e.g., 'utf8', 'base64', or 'hex').

JSON Schema Settings​

These settings affect the output of model_json_schema():

  • title: Sets a custom title for the generated JSON schema.
  • json_schema_extra: A dictionary or callable used to add extra properties to the JSON schema.

Applying Configuration​

Configuration can be applied to different types of entities using several patterns.

Pydantic Models​

For classes inheriting from BaseModel, configuration is defined using the model_config class attribute.

from pydantic import BaseModel, ConfigDict

class User(BaseModel):
model_config = ConfigDict(
strict=True,
str_to_lower=True,
extra='forbid'
)
name: str
email: str

TypedDicts and Dataclasses​

Standard library dataclasses and TypedDict types do not have a model_config attribute. Instead, the @with_config decorator (found in pydantic/config.py) is used to attach configuration to these types.

from typing_extensions import TypedDict
from pydantic import ConfigDict, TypeAdapter, with_config

@with_config(ConfigDict(str_to_lower=True))
class UserDict(TypedDict):
name: str

ta = TypeAdapter(UserDict)
# Input 'ABC' becomes 'abc' due to str_to_lower=True
print(ta.validate_python({'name': 'ABC'}))

TypeAdapters​

When working with types that you cannot modify (like primitive types or third-party classes), you can pass a ConfigDict directly to the TypeAdapter constructor.

from pydantic import TypeAdapter, ConfigDict

ta = TypeAdapter(list[str], config=ConfigDict(str_strip_whitespace=True))
print(ta.validate_python([' hello ', 'world ']))
# Output: ['hello', 'world']

Internal Resolution and Merging​

The ConfigWrapper class in pydantic/_internal/_config.py is responsible for merging configuration across class hierarchies. When a model is created, ConfigWrapper.for_model resolves the final configuration by looking at:

  1. Keyword arguments passed to the class definition.
  2. The model_config attribute in the class namespace.
  3. Configuration inherited from base classes.

The merging logic ensures that child models inherit settings from their parents unless explicitly overridden.

Migration and Compatibility​

This codebase maintains backward compatibility for V1-style class-based configurations. The prepare_config function in pydantic/_internal/_config.py detects if a class-based Config is used and converts it to a ConfigDict, issuing a deprecation warning.

Additionally, several keys have been renamed or removed in this version:

  • orm_mode is now from_attributes.
  • allow_population_by_field_name is now validate_by_name.
  • validate_all is now validate_default.

If a deprecated key is used, the check_deprecated function will trigger a UserWarning detailing the required change.