Core functionality for Pydantic validation and serialization
—
Comprehensive set of functions for building validation schemas for all Python data types. These functions create schema objects that define validation rules, constraints, and transformations for data validation.
Core validation schemas for fundamental Python data types.
def any_schema(*, serialization=None, ref=None) -> AnySchema:
"""
Schema that accepts any value without validation.
Args:
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def none_schema(*, serialization=None, ref=None) -> NoneSchema:
"""
Schema that only accepts None values.
Args:
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def bool_schema(*, strict=None, serialization=None, ref=None) -> BoolSchema:
"""
Boolean validation schema.
Args:
strict: Whether to use strict validation (rejects string 'true'/'false')
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def int_schema(*, strict=None, gt=None, ge=None, lt=None, le=None, multiple_of=None, serialization=None, ref=None) -> IntSchema:
"""
Integer validation schema with optional constraints.
Args:
strict: Whether to reject non-integer types
gt: Value must be greater than this
ge: Value must be greater than or equal to this
lt: Value must be less than this
le: Value must be less than or equal to this
multiple_of: Value must be a multiple of this
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def float_schema(*, strict=None, gt=None, ge=None, lt=None, le=None, multiple_of=None, allow_inf_nan=None, serialization=None, ref=None) -> FloatSchema:
"""
Float validation schema with optional constraints.
Args:
strict: Whether to reject non-float types
gt: Value must be greater than this
ge: Value must be greater than or equal to this
lt: Value must be less than this
le: Value must be less than or equal to this
multiple_of: Value must be a multiple of this
allow_inf_nan: Whether to allow infinity and NaN values
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def str_schema(*, min_length=None, max_length=None, pattern=None, strict=None, strip_whitespace=None, to_lower=None, to_upper=None, regex_engine=None, coerce_numbers_to_str=None, metadata=None, serialization=None, ref=None) -> StrSchema:
"""
String validation schema with length and format constraints.
Args:
min_length: Minimum string length
max_length: Maximum string length
pattern: Regular expression pattern to match (str or Pattern)
strict: Whether to reject non-string types
strip_whitespace: Whether to strip leading/trailing whitespace
to_lower: Whether to convert to lowercase
to_upper: Whether to convert to uppercase
regex_engine: Regex engine to use ('rust-regex' or 'python-re')
coerce_numbers_to_str: Whether to coerce numbers to strings
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def complex_schema(*, strict=None, metadata=None, serialization=None, ref=None) -> ComplexSchema:
"""
Complex number validation schema.
Args:
strict: Whether to reject non-complex types
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def decimal_schema(*, allow_inf_nan=None, multiple_of=None, le=None, ge=None, lt=None, gt=None, max_digits=None, decimal_places=None, strict=None, metadata=None, serialization=None, ref=None) -> DecimalSchema:
"""
Decimal validation schema with precision control.
Args:
allow_inf_nan: Whether to allow infinity and NaN values
multiple_of: Value must be a multiple of this decimal
le: Value must be less than or equal to this
ge: Value must be greater than or equal to this
lt: Value must be less than this
gt: Value must be greater than this
max_digits: Maximum number of digits
decimal_places: Maximum number of decimal places
strict: Whether to reject non-decimal types
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def bytes_schema(*, min_length=None, max_length=None, strict=None, metadata=None, serialization=None, ref=None) -> BytesSchema:
"""
Bytes validation schema with length constraints.
Args:
min_length: Minimum bytes length
max_length: Maximum bytes length
strict: Whether to reject non-bytes types
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""Validation schemas for date, time, and datetime objects.
def date_schema(*, strict=None, gt=None, ge=None, lt=None, le=None, serialization=None, ref=None) -> DateSchema:
"""
Date validation schema.
Args:
strict: Whether to reject non-date types
gt: Date must be greater than this
ge: Date must be greater than or equal to this
lt: Date must be less than this
le: Date must be less than or equal to this
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def time_schema(*, strict=None, gt=None, ge=None, lt=None, le=None, serialization=None, ref=None) -> TimeSchema:
"""
Time validation schema.
Args:
strict: Whether to reject non-time types
gt: Time must be greater than this
ge: Time must be greater than or equal to this
lt: Time must be less than this
le: Time must be less than or equal to this
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def datetime_schema(*, strict=None, gt=None, ge=None, lt=None, le=None, tz_constraint=None, serialization=None, ref=None) -> DatetimeSchema:
"""
Datetime validation schema.
Args:
strict: Whether to reject non-datetime types
gt: Datetime must be greater than this
ge: Datetime must be greater than or equal to this
lt: Datetime must be less than this
le: Datetime must be less than or equal to this
tz_constraint: Timezone constraint ('aware', 'naive', or None)
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def timedelta_schema(*, strict=None, gt=None, ge=None, lt=None, le=None, serialization=None, ref=None) -> TimedeltaSchema:
"""
Timedelta validation schema.
Args:
strict: Whether to reject non-timedelta types
gt: Timedelta must be greater than this
ge: Timedelta must be greater than or equal to this
lt: Timedelta must be less than this
le: Timedelta must be less than or equal to this
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""Validation schemas for lists, sets, tuples, and dictionaries.
def list_schema(items_schema, *, min_length=None, max_length=None, strict=None, serialization=None, ref=None) -> ListSchema:
"""
List validation schema with item validation.
Args:
items_schema: Schema for validating each list item
min_length: Minimum list length
max_length: Maximum list length
strict: Whether to reject non-list types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def set_schema(items_schema=None, *, min_length=None, max_length=None, strict=None, serialization=None, ref=None) -> SetSchema:
"""
Set validation schema with item validation.
Args:
items_schema: Schema for validating each set item
min_length: Minimum set size
max_length: Maximum set size
strict: Whether to reject non-set types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def frozenset_schema(items_schema=None, *, min_length=None, max_length=None, strict=None, serialization=None, ref=None) -> FrozensetSchema:
"""
Frozenset validation schema with item validation.
Args:
items_schema: Schema for validating each frozenset item
min_length: Minimum frozenset size
max_length: Maximum frozenset size
strict: Whether to reject non-frozenset types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def tuple_schema(*items_schemas, extra_schema=None, min_length=None, max_length=None, strict=None, serialization=None, ref=None) -> TupleSchema:
"""
Tuple validation schema with per-position or variable item validation.
Args:
items_schemas: Schemas for each tuple position (fixed-length tuples)
extra_schema: Schema for extra items in variable-length tuples
min_length: Minimum tuple length
max_length: Maximum tuple length
strict: Whether to reject non-tuple types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def dict_schema(keys_schema=None, values_schema=None, *, min_length=None, max_length=None, strict=None, serialization=None, ref=None) -> DictSchema:
"""
Dictionary validation schema with key and value validation.
Args:
keys_schema: Schema for validating dictionary keys
values_schema: Schema for validating dictionary values
min_length: Minimum dictionary size
max_length: Maximum dictionary size
strict: Whether to reject non-dict types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""Schemas for more complex or specialized data types.
def literal_schema(*expected, serialization=None, ref=None) -> LiteralSchema:
"""
Schema that only accepts specific literal values.
Args:
expected: The exact values that are acceptable
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def enum_schema(members, *, strict=None, serialization=None, ref=None) -> EnumSchema:
"""
Enum validation schema.
Args:
members: Enum class or list of enum members
strict: Whether to reject non-enum types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def union_schema(*choices, strict=None, custom_error_type=None, custom_error_message=None, custom_error_context=None, serialization=None, ref=None) -> UnionSchema:
"""
Union validation schema that tries multiple schemas.
Args:
choices: Schema choices to try in order
strict: Whether to use strict validation
custom_error_type: Custom error type for union failures
custom_error_message: Custom error message template
custom_error_context: Custom error context
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def tagged_union_schema(choices, discriminator, *, custom_error_type=None, custom_error_message=None, custom_error_context=None, strict=None, from_attributes=None, serialization=None, ref=None) -> TaggedUnionSchema:
"""
Tagged union schema with discriminator field.
Args:
choices: Mapping of discriminator values to schemas
discriminator: Field name or function to extract discriminator
custom_error_type: Custom error type for failures
custom_error_message: Custom error message template
custom_error_context: Custom error context
strict: Whether to use strict validation
from_attributes: Whether to extract from attributes
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def url_schema(*, max_length=None, allowed_schemes=None, host_required=None, default_host=None, default_port=None, default_path=None, strict=None, serialization=None, ref=None) -> UrlSchema:
"""
URL validation schema.
Args:
max_length: Maximum URL length
allowed_schemes: List of allowed URL schemes
host_required: Whether host is required
default_host: Default host if not provided
default_port: Default port if not provided
default_path: Default path if not provided
strict: Whether to use strict validation
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def uuid_schema(*, version=None, strict=None, serialization=None, ref=None) -> UuidSchema:
"""
UUID validation schema.
Args:
version: Required UUID version (1, 3, 4, or 5)
strict: Whether to reject non-UUID types
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def decimal_schema(*, max_digits=None, decimal_places=None, multiple_of=None, gt=None, ge=None, lt=None, le=None, strict=None, allow_inf_nan=None, serialization=None, ref=None) -> DecimalSchema:
"""
Decimal validation schema.
Args:
max_digits: Maximum number of digits
decimal_places: Maximum decimal places
multiple_of: Value must be multiple of this
gt: Value must be greater than this
ge: Value must be greater than or equal to this
lt: Value must be less than this
le: Value must be less than or equal to this
strict: Whether to reject non-decimal types
allow_inf_nan: Whether to allow infinity and NaN
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""Schemas for complex structured data like models, dataclasses, and typed dictionaries.
def model_schema(cls_name: str, schema: dict, *, model_name=None, config=None, custom_init=None, root_model=False, post_init=None, serialization=None, extra_validator=None, ref=None) -> ModelSchema:
"""
Schema for Pydantic models.
Args:
cls_name: Name of the model class
schema: Dictionary defining model fields
model_name: Display name for the model
config: Model configuration
custom_init: Custom initialization function
root_model: Whether this is a root model
post_init: Post-initialization function
serialization: Custom serialization schema
extra_validator: Additional validation function
ref: Reference name for schema reuse
"""
def model_fields_schema(fields, *, model_name=None, extra_validator=None, serialization=None, ref=None) -> ModelFieldsSchema:
"""
Schema for model fields without a specific model class.
Args:
fields: Dictionary of field names to field schemas
model_name: Display name for the model
extra_validator: Additional validation function
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def dataclass_schema(cls_name: str, schema: dict, *, config=None, serialization=None, ref=None) -> DataclassSchema:
"""
Schema for dataclass validation.
Args:
cls_name: Name of the dataclass
schema: Dictionary defining dataclass fields
config: Validation configuration
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def typed_dict_schema(fields, *, strict=None, extra_behavior=None, total=None, serialization=None, ref=None) -> TypedDictSchema:
"""
Schema for TypedDict validation.
Args:
fields: Dictionary of field names to field schemas
strict: Whether to use strict validation
extra_behavior: How to handle extra fields ('allow', 'forbid', 'ignore')
total: Whether all fields are required by default
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""Additional schema functions for complex validation scenarios.
def literal_schema(expected, *, metadata=None, serialization=None, ref=None) -> LiteralSchema:
"""
Schema for literal value validation.
Args:
expected: List of expected literal values
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def enum_schema(cls, members, *, sub_type=None, missing=None, strict=None, metadata=None, serialization=None, ref=None) -> EnumSchema:
"""
Schema for enum validation.
Args:
cls: The enum class
members: List of enum members
sub_type: Underlying type ('str', 'int', 'float')
missing: Function to handle missing values
strict: Whether to use strict validation
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def union_schema(choices, *, auto_collapse=None, custom_error_type=None, custom_error_message=None, custom_error_context=None, mode=None, metadata=None, serialization=None, ref=None) -> UnionSchema:
"""
Schema for union (multiple choice) validation.
Args:
choices: List of schema choices or tuples of (schema, label)
auto_collapse: Whether to automatically collapse single-choice unions
custom_error_type: Custom error type for validation failures
custom_error_message: Custom error message template
custom_error_context: Custom error context
mode: Union mode ('smart' or 'left_to_right')
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def chain_schema(steps, *, metadata=None, serialization=None, ref=None) -> ChainSchema:
"""
Schema for chaining multiple validation steps.
Args:
steps: List of schemas to apply in sequence
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def lax_or_strict_schema(lax_schema, strict_schema, *, strict=None, metadata=None, serialization=None, ref=None) -> LaxOrStrictSchema:
"""
Schema that chooses between lax and strict validation.
Args:
lax_schema: Schema to use in lax mode
strict_schema: Schema to use in strict mode
strict: Whether to use strict mode by default
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def json_or_python_schema(json_schema, python_schema, *, metadata=None, serialization=None, ref=None) -> JsonOrPythonSchema:
"""
Schema that chooses based on input type (JSON vs Python).
Args:
json_schema: Schema to use for JSON input
python_schema: Schema to use for Python input
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def with_default_schema(schema, *, default=None, default_factory=None, validate_default=None, metadata=None, serialization=None, ref=None) -> WithDefaultSchema:
"""
Schema that provides default values.
Args:
schema: Base schema to apply after setting defaults
default: Default value to use
default_factory: Function to generate default values
validate_default: Whether to validate the default value
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def nullable_schema(schema, *, strict=None, metadata=None, serialization=None, ref=None) -> NullableSchema:
"""
Schema that allows None values in addition to the base schema.
Args:
schema: Base schema to apply for non-None values
strict: Whether to use strict validation
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def uuid_schema(*, version=None, strict=None, metadata=None, serialization=None, ref=None) -> UuidSchema:
"""
UUID validation schema.
Args:
version: UUID version to validate (1, 3, 4, 5, 6, 7, 8)
strict: Whether to reject non-UUID types
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def is_instance_schema(cls, *, cls_repr=None, metadata=None, serialization=None, ref=None) -> IsInstanceSchema:
"""
Schema for isinstance validation.
Args:
cls: Class or classes to check against
cls_repr: String representation of the class
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def callable_schema(*, metadata=None, serialization=None, ref=None) -> CallableSchema:
"""
Schema for callable validation.
Args:
metadata: Additional metadata for the schema
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""from pydantic_core import SchemaValidator
from pydantic_core.core_schema import str_schema, int_schema, bool_schema
# String with constraints
name_schema = str_schema(min_length=1, max_length=50, strip_whitespace=True)
validator = SchemaValidator(name_schema)
result = validator.validate_python(" Alice ") # "Alice"
# Integer with range
age_schema = int_schema(ge=0, le=120)
validator = SchemaValidator(age_schema)
result = validator.validate_python(25) # 25
# Boolean validation
active_schema = bool_schema(strict=True)
validator = SchemaValidator(active_schema)
result = validator.validate_python(True) # Truefrom pydantic_core import SchemaValidator
from pydantic_core.core_schema import list_schema, dict_schema, str_schema, int_schema
# List of strings
names_schema = list_schema(str_schema(min_length=1), min_length=1)
validator = SchemaValidator(names_schema)
result = validator.validate_python(["Alice", "Bob", "Charlie"])
# Dictionary with typed keys and values
scores_schema = dict_schema(
keys_schema=str_schema(min_length=1),
values_schema=int_schema(ge=0, le=100),
min_length=1
)
validator = SchemaValidator(scores_schema)
result = validator.validate_python({"Alice": 95, "Bob": 87, "Charlie": 92})from pydantic_core import SchemaValidator
from pydantic_core.core_schema import (
dict_schema, str_schema, int_schema, list_schema,
union_schema, literal_schema, optional_schema
)
# User profile schema
user_schema = dict_schema({
'id': int_schema(gt=0),
'name': str_schema(min_length=1, max_length=100),
'email': str_schema(pattern=r'^[^@]+@[^@]+\.[^@]+$'),
'age': union_schema(int_schema(ge=0, le=120), none_schema()),
'status': literal_schema('active', 'inactive', 'pending'),
'tags': list_schema(str_schema(min_length=1))
})
validator = SchemaValidator(user_schema)
# Valid user data
user_data = {
'id': 123,
'name': 'Alice Johnson',
'email': 'alice@example.com',
'age': 30,
'status': 'active',
'tags': ['developer', 'python', 'ai']
}
result = validator.validate_python(user_data)
print(result)from pydantic_core import SchemaValidator
from pydantic_core.core_schema import model_schema, str_schema, int_schema
# Define a model schema
person_model = model_schema(
cls_name='Person',
schema={
'name': str_schema(min_length=1),
'age': int_schema(ge=0),
'email': str_schema()
}
)
validator = SchemaValidator(person_model)
# Validate model data
person_data = {'name': 'John', 'age': 25, 'email': 'john@example.com'}
result = validator.validate_python(person_data)
print(result) # Validated person dataAdditional schema functions for advanced validation scenarios.
def chain_schema(*steps, serialization=None, ref=None) -> ChainSchema:
"""
Chain multiple validation steps together.
Args:
steps: Sequence of validation schemas to apply in order
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def lax_or_strict_schema(lax_schema, strict_schema, *, serialization=None, ref=None) -> LaxOrStrictSchema:
"""
Schema that uses different validation based on strict/lax mode.
Args:
lax_schema: Schema to use in lax mode
strict_schema: Schema to use in strict mode
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def json_or_python_schema(json_schema, python_schema, *, serialization=None, ref=None) -> JsonOrPythonSchema:
"""
Schema that uses different validation for JSON vs Python input.
Args:
json_schema: Schema for JSON input
python_schema: Schema for Python object input
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def definitions_schema(schema, definitions, *, serialization=None, ref=None) -> DefinitionsSchema:
"""
Schema with reusable definitions.
Args:
schema: Main validation schema
definitions: Dictionary of reusable schema definitions
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""
def definition_reference_schema(schema_ref, *, serialization=None, ref=None) -> DefinitionReferenceSchema:
"""
Reference to a schema definition.
Args:
schema_ref: Reference name of the schema definition
serialization: Custom serialization schema
ref: Reference name for schema reuse
"""Install with Tessl CLI
npx tessl i tessl/pypi-pydantic-core