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:
- BaseModel: Define a
model_configclass attribute.from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str - Pydantic Dataclasses: Pass the
configargument to the decorator.from pydantic.dataclasses import dataclass
@dataclass(config=ConfigDict(str_to_lower=True))
class Item:
name: str - TypeAdapter: Pass the
configargument during instantiation.from pydantic import TypeAdapter, ConfigDict
ta = TypeAdapter(list[str], config=ConfigDict(str_max_length=10)) - TypedDict and Stdlib Dataclasses: Use the
with_configdecorator frompydantic/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: WhenTrue, Pydantic avoids type coercion (e.g., it won't turn the string"123"into an integer123).extra: Controls how extra fields in the input are handled. Options are'ignore'(default),'allow'(stored in__pydantic_extra__), or'forbid'(raises aValidationError).revalidate_instances: Determines if instances of models or dataclasses should be re-validated when passed as input. Defaults to'never'.validate_assignment: IfTrue, 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 ofdatetime,date,time, andtimedeltain JSON. Options include'iso8601'(default),'seconds', and'milliseconds'.ser_json_bytes: Determines howbytesare encoded in JSON. Options are'utf8','base64', or'hex'.serialize_by_alias: IfTrue, 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 toTrue.validate_by_name: Whether a field can be populated using its attribute name. Defaults toFalse.populate_by_name: (Deprecated in v2.11+) Usevalidate_by_nameinstead.
[!WARNING] You cannot set both
validate_by_aliasandvalidate_by_nametoFalse. 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:
- Keyword arguments passed to the class definition.
- The
model_configattribute in the class namespace. - The
model_configattributes 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:
| Key | Default Value |
|---|---|
strict | False |
extra | None (effectively 'ignore') |
loc_by_alias | True |
protected_namespaces | ('model_validate', 'model_dump') |
regex_engine | 'rust-regex' |
cache_strings | True |
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.