Skip to main content

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 to True, the validator will not attempt to coerce types (e.g., it won't convert the string "42" to an integer 42).
  • extra_fields_behavior: Controls how TypedDict, Model, and Dataclass schemas handle fields not defined in the schema. It accepts values from the ExtraBehavior type: '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: If True, numeric types (int, float) will be coerced to strings when a string is expected. This is ignored if strict mode 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 for datetime, date, time, and timedelta. Options include 'iso8601', 'seconds', and 'milliseconds'.
  • ser_json_timedelta: Specifically for timedelta (either 'iso8601' or 'float'). Note that ser_json_temporal takes precedence if both are set.
  • ser_json_bytes: Controls how bytes are encoded in JSON ('utf8', 'base64', or 'hex').

Special Float Values

  • ser_json_inf_nan: Determines how Infinity and NaN are represented in JSON.
    • 'null': Serializes to null (default).
    • 'constants': Serializes to Infinity, -Infinity, or NaN.
    • '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.

LevelExamplePriority
Field/Schema Levelcs.str_schema(max_length=5)Highest
Global ConfigCoreConfig(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

AttributeTypeDefaultDescription
strictboolFalseEnable strict validation globally.
extra_fields_behaviorExtraBehavior'ignore'How to handle extra fields ('allow', 'forbid', 'ignore').
from_attributesboolFalseExtract values from object attributes.
validate_defaultboolFalseValidate default values.
allow_inf_nanboolTrueAllow inf and nan for floats.
cache_stringsbool | LiteralTrueEnable string caching for performance.
regex_engineLiteral'rust-regex'Engine for regex patterns ('rust-regex', 'python-re').