Skip to main content

Global Scalar Configuration

To set global behaviors for scalar types like strings, numbers, and dates across your entire schema, use the CoreConfig class. This configuration is passed to SchemaValidator or SchemaSerializer to enforce consistent rules without repeating them in every field definition.

Configure Global String Constraints

You can control string length, whitespace handling, and casing globally by setting attributes in CoreConfig.

from pydantic_core import CoreConfig, SchemaValidator
from pydantic_core import core_schema as cs

# Apply global string constraints
config = CoreConfig(
str_max_length=10,
str_strip_whitespace=True,
str_to_lower=True
)

v = SchemaValidator(cs.str_schema(), config=config)

# Validates and transforms: strips whitespace and converts to lowercase
assert v.validate_python(' HELLO ') == 'hello'

# Fails global length constraint
# v.validate_python('this string is too long')

Key string configuration options include:

  • str_max_length / str_min_length: Global bounds for all string fields.
  • str_strip_whitespace: Automatically trims leading/trailing whitespace.
  • str_to_lower / str_to_upper: Automatically transforms string casing during validation.

Control Number Validation and Coercion

CoreConfig allows you to toggle global support for special float values and enable coercion from numbers to strings.

from pydantic_core import CoreConfig, SchemaValidator
from pydantic_core import core_schema as cs

# Disable infinity/NaN and enable number-to-string coercion
config = CoreConfig(
allow_inf_nan=False,
coerce_numbers_to_str=True
)

# Coercion example
v_str = SchemaValidator(cs.str_schema(), config=config)
assert v_str.validate_python(123) == '123'

# Infinity check example
v_float = SchemaValidator(cs.float_schema(), config=config)
# This will raise a ValidationError because allow_inf_nan is False
# v_float.validate_python(float('inf'))

Customize Temporal Serialization

You can change how datetime, date, time, and timedelta objects are serialized to JSON (e.g., using Unix timestamps instead of ISO8601).

from datetime import datetime
from pydantic_core import CoreConfig, SchemaSerializer, core_schema as cs

# Configure global temporal serialization to Unix timestamps (seconds)
config = CoreConfig(ser_json_temporal='seconds')
s = SchemaSerializer(cs.datetime_schema(), config=config)

dt = datetime(2024, 1, 1, 0, 0, 0)
assert s.to_json(dt) == b'1704067200.0'

Available ser_json_temporal options:

  • 'iso8601': Default ISO format.
  • 'seconds': Unix timestamp in seconds.
  • 'milliseconds': Unix timestamp in milliseconds.

Handle Special Values in Serialization

Use CoreConfig to define how bytes and special float values (like NaN) should appear in JSON output.

from pydantic_core import CoreConfig, SchemaSerializer, core_schema as cs

# Configure bytes as hex and NaN as strings for valid JSON
config = CoreConfig(
ser_json_bytes='hex',
ser_json_inf_nan='strings'
)

s_bytes = SchemaSerializer(cs.bytes_schema(), config=config)
assert s_bytes.to_json(b'foo') == b'"666f6f"'

s_float = SchemaSerializer(cs.float_schema(), config=config)
assert s_float.to_json(float('nan')) == b'"NaN"'

Priority of Field-Level Constraints

Field-specific constraints defined in the schema always take priority over global CoreConfig settings.

from pydantic_core import CoreConfig, SchemaValidator
from pydantic_core import core_schema as cs

# Global max length is 10, but field-level is 5
config = CoreConfig(str_max_length=10)
schema = cs.str_schema(max_length=5)

v = SchemaValidator(schema, config=config)

# This fails because the field-level constraint (5) overrides the global (10)
# v.validate_python('123456')

Troubleshooting

  • Strict Mode and Coercion: The coerce_numbers_to_str setting is ignored if strict mode is enabled (either globally in CoreConfig or on the specific field).
  • Temporal Precedence: If both ser_json_temporal and ser_json_timedelta are provided, ser_json_temporal takes precedence for timedelta types.
  • JSON Compatibility: Using ser_json_inf_nan='constants' produces Infinity and NaN in JSON, which is technically invalid according to the JSON spec. Use 'strings' or 'null' for standard-compliant output.