The CoreConfig Object
The CoreConfig object is the central configuration hub for controlling validation and serialization behavior in pydantic-core. Defined as a TypedDict in pydantic_core/core_schema.py, it allows developers to set global or local defaults for how data is processed, ranging from strictness levels to specific JSON serialization formats.
Application Scopes
Configuration can be applied at two primary levels: globally for an entire schema validator or locally for specific complex types.
Global Configuration
When initializing a SchemaValidator, you can pass a CoreConfig object as the config argument. This configuration applies to the entire schema unless overridden by more specific settings.
from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs
# Global configuration enforcing a maximum string length
v = SchemaValidator(
cs.str_schema(),
config=CoreConfig(str_max_length=5)
)
assert v.isinstance_python('test') is True
assert v.isinstance_python('too long') is False
Local Configuration
Specific schema types like ModelSchema, DataclassSchema, and TypedDictSchema include a config field. This allows for granular control over how a particular model or dataclass behaves, independent of the global validator settings.
class MyModel:
__slots__ = ('__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__')
# Local configuration within a ModelSchema
schema = cs.model_schema(
cls=MyModel,
config=CoreConfig(str_max_length=5),
schema=cs.model_fields_schema(
fields={'a': cs.model_field(schema=cs.str_schema())},
),
)
v = SchemaValidator(schema)
Key Configuration Categories
CoreConfig groups settings into several functional areas:
Validation Control
These settings influence how the validator interprets input data:
strict: WhenTrue, the validator avoids type coercion (e.g., it won't convert a string "123" to an integer).extra_fields_behavior: Controls howModelSchemaandTypedDictSchemahandle fields not defined in the schema. Options are'allow','forbid', or'ignore'.revalidate_instances: Specifically for models and dataclasses, this determines if already instantiated objects should be re-validated. It can be set to'always','never', or'subclass-instances'.hide_input_in_errors: IfTrue, the original input data is omitted fromValidationErrormessages, which is useful for protecting sensitive data in logs.
Type-Specific Constraints
CoreConfig provides defaults for specific data types, which is often more efficient than defining them on every individual field:
- Strings:
str_max_length,str_min_length,str_strip_whitespace,str_to_lower, andstr_to_upper. - Floats:
allow_inf_nan(defaults toTrue) controls whetherNaNandInfinityare accepted. - Numbers:
coerce_numbers_to_strenables converting numeric types to strings during validation.
Serialization Behavior
Settings prefixed with ser_json_ control how data is transformed into JSON:
ser_json_timedelta: Options include'iso8601'or'float'.ser_json_bytes: Options include'utf8','base64', or'hex'.ser_json_inf_nan: Determines how non-finite floats are represented in JSON ('null','constants', or'strings').
Integration with Schema Types
The following core schemas explicitly support the config attribute:
ModelSchema
In ModelSchema, the config object controls the behavior of the model fields and the model instance itself. It works alongside fields like extra_behavior and revalidate_instances which can also be set directly on the ModelSchema.
DataclassSchema
Similar to models, DataclassSchema uses CoreConfig to manage validation rules for the dataclass fields. It also includes dataclass-specific flags like slots and frozen.
TypedDictSchema
TypedDictSchema uses CoreConfig but also provides direct fields for common settings. For example, TypedDictSchema has a total field, while CoreConfig has a typed_dict_total field. The schema-level fields typically act as shortcuts or overrides for the configuration dictionary.
Precedence and Overrides
A critical aspect of CoreConfig is that field-level constraints always take precedence. If a specific str_schema defines a max_length, it will override the str_max_length set in the CoreConfig.
# Field-level max_length (5) overrides Config-level str_max_length (10)
v = SchemaValidator(
cs.str_schema(max_length=5),
config=CoreConfig(str_max_length=10)
)
assert v.isinstance_python('12345') is True
assert v.isinstance_python('123456') is False # Fails due to field-level constraint
This hierarchy allows you to set sensible defaults for an entire application or model while still allowing specific fields to deviate from those defaults when necessary.