Validating Scalar Types
Scalar types are the fundamental building blocks for schemas in this codebase. You configure them using specific schema functions from the core_schema module and validate them using the SchemaValidator.
Basic Usage
To validate a scalar type, define a schema using the appropriate helper function and pass it to SchemaValidator.
from pydantic_core import SchemaValidator, core_schema
# Define a simple integer schema
schema = core_schema.int_schema()
v = SchemaValidator(schema)
# Validate python objects
assert v.validate_python(123) == 123
Numeric Validation
Numeric schemas support range constraints (ge, le, gt, lt) and divisibility checks (multiple_of).
Integers
The int_schema validates integer values. In lax mode, it coerces strings and floats (without fractional parts) to integers.
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.int_schema(ge=10, le=100, multiple_of=5)
v = SchemaValidator(schema)
assert v.validate_python('15') == 15
assert v.validate_python(20.0) == 20
Note on Large Integers: To prevent DDoS attacks, string-to-integer parsing is limited to 4300 digits. Exceeding this limit will trigger an int_parsing_size error.
Floats
The float_schema handles floating-point numbers. Use allow_inf_nan to control the acceptance of non-finite numbers.
from pydantic_core import SchemaValidator, core_schema
# Disallow NaN and Infinity (allowed by default)
schema = core_schema.float_schema(allow_inf_nan=False)
v = SchemaValidator(schema)
# This will raise a ValidationError
# v.validate_python(float('nan'))
Decimals
The decimal_schema validates decimal.Decimal objects. It includes specific constraints for precision.
from decimal import Decimal
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.decimal_schema(max_digits=5, decimal_places=2)
v = SchemaValidator(schema)
assert v.validate_python('123.45') == Decimal('123.45')
String and Bytes Validation
Strings
The str_schema provides extensive support for length constraints, regex patterns, and transformations.
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.str_schema(
min_length=3,
max_length=10,
pattern=r'^[a-z]+$',
strip_whitespace=True,
to_upper=True
)
v = SchemaValidator(schema)
# Whitespace is stripped before length and pattern checks
assert v.validate_python(' abc ') == 'ABC'
Bytes
The bytes_schema validates bytes and bytearray objects, supporting length constraints.
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.bytes_schema(min_length=2, max_length=5)
v = SchemaValidator(schema)
assert v.validate_python(b'hello') == b'hello'
Boolean and None
Booleans
The bool_schema validates boolean values. In lax mode, it accepts a variety of truthy/falsy values.
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(core_schema.bool_schema())
# Lax mode coercions
assert v.validate_python('yes') is True
assert v.validate_python(0) is False
assert v.validate_python('true') is True
None
The none_schema ensures the value is exactly None.
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(core_schema.none_schema())
assert v.validate_python(None) is None
Complex Numbers
The complex_schema validates complex numbers and can coerce them from strings.
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(core_schema.complex_schema())
assert v.validate_python('1+2j') == complex(1, 2)
Troubleshooting and Gotchas
Transformation Order in Strings
In str_schema, transformations and constraints are applied in a specific order:
strip_whitespace: Applied first. Length and pattern checks see the stripped string.min_length/max_length: Checked after stripping.pattern: Checked after stripping.to_lower/to_upper: Applied after validation. This means yourpatternmust match the original (or stripped) case, not the transformed case.
# This will FAIL because 'ABC' does not match '^[a-z]+$'
# even though to_lower=True is set.
schema = core_schema.str_schema(pattern=r'^[a-z]+$', to_lower=True)
v = SchemaValidator(schema)
# v.validate_python('ABC') # Raises ValidationError
Regex Engines
By default, str_schema uses the rust-regex engine (based on the Rust regex crate), which is highly performant and DDoS-resistant but does not support features like look-arounds or backtracking. If you need these features, switch to the Python engine:
schema = core_schema.str_schema(pattern=r'(?<=foo)bar', regex_engine='python-re')
Float to Int Coercion
In lax mode, a float can be coerced to an int only if it has no fractional part.
1.0succeeds and becomes1.1.1fails validation forint_schema.
Decimal Constraints
If allow_inf_nan is set to True in decimal_schema, you cannot use max_digits or decimal_places constraints, as these are undefined for infinity and NaN.