Global Engine Configuration
CoreConfig is a central TypedDict defined in pydantic_core.core_schema that governs the global behavior of both SchemaValidator and SchemaSerializer. It allows developers to define default policies for validation (such as strictness and extra field handling) and serialization (such as JSON formatting for dates and bytes) across an entire schema tree.
While individual schema elements (like StringSchema or IntSchema) can often override these settings, CoreConfig provides the baseline configuration for the engine.
Validation Control
The primary role of CoreConfig is to establish the validation "strictness" and how the engine handles unexpected data.
Strictness and Extra Fields
strict: When set toTrue, the validator will not attempt to coerce types (e.g., it won't convert the string"42"to an integer42).extra_fields_behavior: Controls howTypedDict,Model, andDataclassschemas handle fields not defined in the schema. It accepts values from theExtraBehaviortype:'allow','forbid', or'ignore'.
from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs
# Forbid extra fields globally
config = CoreConfig(extra_fields_behavior='forbid')
schema = cs.typed_dict_schema({'a': cs.typed_dict_field(cs.int_schema())})
v = SchemaValidator(schema, config=config)
# This will raise a ValidationError because 'b' is not defined
# v.validate_python({'a': 1, 'b': 2})
Alias Handling
validate_by_alias: Whether to use field aliases during validation (default:True).validate_by_name: Whether to allow validation using the internal field name even if an alias is defined (default:False).loc_by_alias: Determines if error locations (loc) should use the alias or the field name.
String Processing
CoreConfig provides several global toggles for string validation, which are particularly useful for cleaning input data consistently.
str_strip_whitespace: Automatically strips leading and trailing whitespace from all string inputs.str_to_lower/str_to_upper: Converts all strings to lowercase or uppercase.str_max_length/str_min_length: Sets global bounds on string length.
from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs
config = CoreConfig(str_strip_whitespace=True, str_to_upper=True)
v = SchemaValidator(cs.str_schema(), config=config)
assert v.validate_python(' hello ') == 'HELLO'
Type Coercion
A key feature of pydantic-core is its ability to coerce types in non-strict mode. CoreConfig controls specific coercion behaviors:
coerce_numbers_to_str: IfTrue, numeric types (int, float) will be coerced to strings when a string is expected. This is ignored ifstrictmode is enabled.
from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs
config = CoreConfig(coerce_numbers_to_str=True)
v = SchemaValidator(cs.str_schema(), config=config)
assert v.validate_python(42) == '42'
Serialization Settings
CoreConfig also influences how SchemaSerializer produces JSON output, specifically for types that don't have a native JSON representation.
Temporal and Bytes Formatting
ser_json_temporal: Controls serialization fordatetime,date,time, andtimedelta. Options include'iso8601','seconds', and'milliseconds'.ser_json_timedelta: Specifically fortimedelta(either'iso8601'or'float'). Note thatser_json_temporaltakes precedence if both are set.ser_json_bytes: Controls howbytesare encoded in JSON ('utf8','base64', or'hex').
Special Float Values
ser_json_inf_nan: Determines howInfinityandNaNare represented in JSON.'null': Serializes tonull(default).'constants': Serializes toInfinity,-Infinity, orNaN.'strings': Serializes to"Infinity","-Infinity", or"NaN".
from pydantic_core import CoreConfig, SchemaSerializer, core_schema as cs
config = CoreConfig(ser_json_inf_nan='constants')
s = SchemaSerializer(cs.any_schema(), config=config)
assert s.to_json(float('inf')) == b'Infinity'
Configuration Precedence
Settings in CoreConfig act as defaults. If a specific field or schema defines the same attribute, the field-level setting takes precedence.
| Level | Example | Priority |
|---|---|---|
| Field/Schema Level | cs.str_schema(max_length=5) | Highest |
| Global Config | CoreConfig(str_max_length=10) | Lowest |
In the following example, the validator will enforce a maximum length of 5, overriding the global config of 10:
from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs
config = CoreConfig(str_max_length=10)
# Field-level override
v = SchemaValidator(cs.str_schema(max_length=5), config=config)
assert v.isinstance_python('12345') is True
assert v.isinstance_python('123456') is False
Reference Table
| Attribute | Type | Default | Description |
|---|---|---|---|
strict | bool | False | Enable strict validation globally. |
extra_fields_behavior | ExtraBehavior | 'ignore' | How to handle extra fields ('allow', 'forbid', 'ignore'). |
from_attributes | bool | False | Extract values from object attributes. |
validate_default | bool | False | Validate default values. |
allow_inf_nan | bool | True | Allow inf and nan for floats. |
cache_strings | bool | Literal | True | Enable string caching for performance. |
regex_engine | Literal | 'rust-regex' | Engine for regex patterns ('rust-regex', 'python-re'). |