Skip to main content

Core Configuration

Core configuration in this project is centered around the ConfigDict and how it is processed by the internal ConfigWrapper. Configuration options control everything from how strings are stripped during validation to how temporal types are formatted during JSON serialization.

The ConfigDict

The primary interface for configuration is the ConfigDict class, defined in pydantic/config.py. It is a TypedDict that provides type-safe keys for all available configuration options.

from pydantic import ConfigDict

config = ConfigDict(
strict=True,
extra='forbid',
str_strip_whitespace=True
)

Application Methods

Configuration can be applied to various Pydantic entities using different patterns:

  1. BaseModel: Define a model_config class attribute.
    from pydantic import BaseModel, ConfigDict

    class User(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str
  2. Pydantic Dataclasses: Pass the config argument to the decorator.
    from pydantic.dataclasses import dataclass

    @dataclass(config=ConfigDict(str_to_lower=True))
    class Item:
    name: str
  3. TypeAdapter: Pass the config argument during instantiation.
    from pydantic import TypeAdapter, ConfigDict

    ta = TypeAdapter(list[str], config=ConfigDict(str_max_length=10))
  4. TypedDict and Stdlib Dataclasses: Use the with_config decorator from pydantic/config.py. This decorator sets the __pydantic_config__ attribute on the class, which Pydantic looks for when generating schemas.
    from typing_extensions import TypedDict
    from pydantic import with_config, ConfigDict

    @with_config(ConfigDict(extra='allow'))
    class LegacyData(TypedDict):
    id: int

Core Configuration Categories

Validation Behavior

Validation settings control how Pydantic interprets and coerces input data.

  • strict: When True, Pydantic avoids type coercion (e.g., it won't turn the string "123" into an integer 123).
  • extra: Controls how extra fields in the input are handled. Options are 'ignore' (default), 'allow' (stored in __pydantic_extra__), or 'forbid' (raises a ValidationError).
  • revalidate_instances: Determines if instances of models or dataclasses should be re-validated when passed as input. Defaults to 'never'.
  • validate_assignment: If True, Pydantic re-validates the entire model whenever an attribute is changed.
  • protected_namespaces: A tuple of prefixes or regex patterns that prevent field names from colliding with Pydantic's internal methods. The default is ('model_validate', 'model_dump').

Serialization Behavior

Serialization settings influence the output of model_dump() and model_dump_json().

  • ser_json_temporal: Controls the format of datetime, date, time, and timedelta in JSON. Options include 'iso8601' (default), 'seconds', and 'milliseconds'.
  • ser_json_bytes: Determines how bytes are encoded in JSON. Options are 'utf8', 'base64', or 'hex'.
  • serialize_by_alias: If True, fields are serialized using their defined aliases by default.

Alias Management

Pydantic provides fine-grained control over how aliases are used for both validation and serialization.

  • validate_by_alias: Whether a field can be populated using its alias. Defaults to True.
  • validate_by_name: Whether a field can be populated using its attribute name. Defaults to False.
  • populate_by_name: (Deprecated in v2.11+) Use validate_by_name instead.

[!WARNING] You cannot set both validate_by_alias and validate_by_name to False. This would make the field impossible to populate.

Internal Mechanics: ConfigWrapper

The ConfigWrapper class in pydantic/_internal/_config.py is the internal engine that manages configuration merging and defaults.

Configuration Merging

When a model is created, ConfigWrapper.for_model merges configurations from several sources in descending order of priority:

  1. Keyword arguments passed to the class definition.
  2. The model_config attribute in the class namespace.
  3. The model_config attributes of base classes.

Default Values

If a configuration key is not explicitly provided, Pydantic falls back to config_defaults defined in pydantic/_internal/_config.py. Some notable defaults include:

KeyDefault Value
strictFalse
extraNone (effectively 'ignore')
loc_by_aliasTrue
protected_namespaces('model_validate', 'model_dump')
regex_engine'rust-regex'
cache_stringsTrue

Core Schema Integration

The ConfigWrapper.core_config method translates the high-level ConfigDict into a pydantic_core.core_schema.CoreConfig object. This object is passed directly to the underlying Rust-based pydantic-core validator and serializer, ensuring that configuration settings are enforced at the highest performance level.