Configuring Validation Strictness
Validation strictness in this codebase is controlled through the strict and validate_default settings. By default, validation is "lax," meaning the validator attempts to coerce data into the target type (e.g., converting the string "123" to the integer 123).
Configuring Global Strictness
You can enforce strict validation across an entire schema by setting strict=True in the CoreConfig passed to the SchemaValidator.
from pydantic_core import SchemaValidator, core_schema, ValidationError
# Global strict mode enabled
v = SchemaValidator(
core_schema.int_schema(),
config=core_schema.CoreConfig(strict=True)
)
# This will fail because it's a string, not an int
try:
v.validate_python('123')
except ValidationError as e:
print(e)
# Input should be a valid integer [type=int_parsing, input_value='123', input_type=str]
Overriding Strictness for Specific Fields
Strictness can be controlled at the individual schema level, which takes precedence over the global configuration.
from pydantic_core import SchemaValidator, core_schema
# Global is lax, but this specific field is strict
v = SchemaValidator(
core_schema.typed_dict_schema({
'age': core_schema.typed_dict_field(core_schema.int_schema(strict=True)),
'name': core_schema.typed_dict_field(core_schema.str_schema())
}),
config=core_schema.CoreConfig(strict=False)
)
# 'name' is coerced (lax), but 'age' must be an int (strict)
v.validate_python({'age': 25, 'name': 123}) # OK: name becomes "123"
# v.validate_python({'age': '25', 'name': 'John'}) # Raises ValidationError for 'age'
Validating Default Values
By default, default values provided in with_default_schema are not validated. To ensure defaults also satisfy the schema constraints, use the validate_default setting.
Enabling Globally via Config
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(
core_schema.with_default_schema(
core_schema.int_schema(gt=10),
default=5
),
config=core_schema.CoreConfig(validate_default=True)
)
# This will raise a ValidationError because the default value 5 is not > 10
try:
v.validate_python({})
except ValidationError as e:
print(e)
# Input should be greater than 10 [type=greater_than, input_value=5, input_type=int]
Enabling Locally via Schema
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(
core_schema.with_default_schema(
core_schema.int_schema(),
default='42',
validate_default=True
)
)
# The default '42' is validated and coerced to the integer 42
assert v.validate_python({}) == 42
Type-Specific Strictness Behaviors
Different core types have specific behaviors when switching between lax and strict modes.
Boolean Validation
In lax mode, BoolSchema accepts various truthy/falsy values. In strict mode, it only accepts True or False.
from pydantic_core import SchemaValidator, core_schema
# Lax Bool (Default)
lax_v = SchemaValidator(core_schema.bool_schema())
assert lax_v.validate_python('yes') is True
assert lax_v.validate_python(1) is True
# Strict Bool
strict_v = SchemaValidator(core_schema.bool_schema(strict=True))
# strict_v.validate_python('yes') # Raises ValidationError
assert strict_v.validate_python(True) is True
String Coercion
The StringSchema supports coerce_numbers_to_str, which allows numeric types to be converted to strings in lax mode.
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(
core_schema.str_schema(coerce_numbers_to_str=True)
)
assert v.validate_python(123) == "123"
assert v.validate_python(12.5) == "12.5"
Troubleshooting and Gotchas
- Precedence: A
strictsetting on an individual schema (e.g.,IntSchema) always overrides thestrictsetting inCoreConfig. - Coercion Conflict: The
coerce_numbers_to_strsetting is ignored ifstrictmode is enabled (either globally or locally). In strict mode, only actual string inputs are accepted forStringSchema. - JSON vs Python: In JSON validation (
validate_json), strictness rules are sometimes slightly different because JSON has fewer native types. For example, dictionary keys are always strings in JSON and may be coerced even if the schema expects integers. - Default Validation: If
validate_defaultisTrueand the default value is a string"42"for anIntSchema, it will succeed in lax mode (via coercion) but fail ifstrict=Trueis also set.