Skip to main content

Global Configuration

Global configuration in pydantic-core is managed through the CoreConfig class, a TypedDict defined in pydantic_core.core_schema. This configuration controls the behavior of both validation (via SchemaValidator) and serialization (via SchemaSerializer).

Application Scopes

Configuration can be applied at different levels of the schema hierarchy.

Global Level

When initializing a SchemaValidator or SchemaSerializer, you can provide a config argument. This configuration applies to the entire schema unless overridden at a lower level.

from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs

# Global configuration for string length
config = CoreConfig(str_max_length=5)
v = SchemaValidator(cs.str_schema(), config=config)

assert v.isinstance_python('test') is True
assert v.isinstance_python('too long') is False

Model and Dataclass Level

Configuration can also be embedded within specific schemas, such as model_schema or dataclass_schema. This allows for localized behavior that differs from the global settings.

from pydantic_core import CoreConfig, SchemaValidator, core_schema as cs

class MyModel:
pass

v = SchemaValidator(
cs.model_schema(
cls=MyModel,
config=CoreConfig(extra_fields_behavior='forbid'),
schema=cs.model_fields_schema(fields={
'f': cs.model_field(schema=cs.str_schema())
}),
)
)

Validation Configuration

CoreConfig provides several attributes to tune validation behavior across various types.

Strictness and Coercion

  • strict: When set to True, the validator will not attempt to coerce types (e.g., it won't convert the string "123" to an integer for an int_schema).
  • coerce_numbers_to_str: Specifically enables coercion of numeric types to strings when not in strict mode.

Handling Extra Fields

The extra_fields_behavior attribute (using the ExtraBehavior type) determines how TypedDict and model schemas handle fields not defined in the schema:

  • 'allow': Extra fields are kept.
  • 'ignore': Extra fields are discarded.
  • 'forbid': Validation fails if extra fields are present.

String and Numeric Constraints

Global constraints can be set for all applicable fields:

  • Strings: str_max_length, str_min_length, str_strip_whitespace, str_to_lower, and str_to_upper.
  • Floats: allow_inf_nan (defaults to True) controls whether Infinity and NaN are accepted.

Serialization Configuration

Configuration also dictates how data is transformed into JSON via SchemaSerializer.

JSON Formatting

  • Temporal Types: ser_json_temporal controls the format for datetime, date, time, and timedelta. It accepts 'iso8601', 'seconds', or 'milliseconds'.
  • Bytes: ser_json_bytes defines how bytes are serialized ('utf8', 'base64', or 'hex').
  • Special Floats: ser_json_inf_nan determines how non-finite floats are represented in JSON ('null', 'constants', or 'strings').
from pydantic_core import CoreConfig, SchemaSerializer, core_schema as cs

# Configure JSON serialization of Inf/NaN as constants
config = CoreConfig(ser_json_inf_nan='constants')
s = SchemaSerializer(cs.float_schema(), config=config)

assert s.to_json(float('inf')) == b'Infinity'

Error Handling and Metadata

CoreConfig influences how ValidationError objects are constructed and represented.

  • hide_input_in_errors: If True, the input data that caused the error is omitted from the ValidationError representation, which is useful for sensitive data.
  • loc_by_alias: Determines whether error locations (loc) use the field's alias or its internal name. Defaults to True.
  • validation_error_cause: If enabled, the original Python exception that caused a validation failure is added to the __cause__ of the ValidationError.

Precedence and Overrides

A key principle in pydantic-core is that field-level constraints take priority over global configuration.

If a str_schema defines its own max_length, that value will be used even if CoreConfig specifies a different str_max_length.

# Field-level max_length (3) overrides global str_max_length (5)
v = SchemaValidator(
cs.str_schema(max_length=3),
config=CoreConfig(str_max_length=5)
)

assert v.isinstance_python('test') is False # Fails because 4 > 3

Accessing Configuration in Custom Validators

When using functional validators (like with_info_plain_validator_function), the active CoreConfig is accessible via the config property of the ValidationInfo object.

from pydantic_core import core_schema as cs

def my_validator(value, info: cs.ValidationInfo):
# Access the active configuration
if info.config and info.config.get('strict'):
# perform strict-specific logic
pass
return value