Core functionality for Pydantic validation and serialization
—
Core classes for validating data against schemas and serializing validated data to various output formats. These are the main classes that most users will interact with when using pydantic-core directly.
The primary validation class that validates Python data, JSON data, or string data against defined schemas. It provides fast validation with detailed error reporting.
class SchemaValidator:
def __init__(self, schema: CoreSchema, config: CoreConfig = None):
"""
Create a new schema validator.
Args:
schema: The validation schema to use
config: Optional configuration for validation behavior
"""
def validate_python(self, value, *, strict=None, from_attributes=None, context=None, self_instance=None, allow_partial=False, by_alias=None, by_name=None):
"""
Validate a Python object against the schema.
Args:
value: The Python object to validate
strict: Whether to use strict validation (overrides config)
from_attributes: Whether to extract values from object attributes
context: Additional context for validation
self_instance: An instance of a model to set attributes on from validation
allow_partial: Whether to allow partial validation (bool or 'off'/'on'/'trailing-strings')
by_alias: Whether to use field aliases when validating
by_name: Whether to use field names when validating
Returns:
The validated and potentially transformed value
Raises:
ValidationError: If validation fails
"""
def isinstance_python(self, value, *, strict=None, from_attributes=None, context=None, self_instance=None, by_alias=None, by_name=None) -> bool:
"""
Similar to validate_python but returns a boolean instead of raising ValidationError.
Args:
value: The Python object to validate
strict: Whether to use strict validation (overrides config)
from_attributes: Whether to extract values from object attributes
context: Additional context for validation
self_instance: An instance of a model to set attributes on from validation
by_alias: Whether to use field aliases when validating
by_name: Whether to use field names when validating
Returns:
True if validation succeeds, False if validation fails
"""
def validate_json(self, json_data, *, strict=None, context=None, self_instance=None, allow_partial=False, by_alias=None, by_name=None):
"""
Validate JSON data against the schema.
Args:
json_data: JSON string, bytes, or bytearray to validate
strict: Whether to use strict validation (overrides config)
context: Additional context for validation
self_instance: An instance of a model to set attributes on from validation
allow_partial: Whether to allow partial validation (bool or 'off'/'on'/'trailing-strings')
by_alias: Whether to use field aliases when validating
by_name: Whether to use field names when validating
Returns:
The validated Python object
Raises:
ValidationError: If validation fails
"""
def validate_strings(self, str_data, *, strict=None, context=None, allow_partial=False, by_alias=None, by_name=None):
"""
Validate string data against the schema.
Args:
str_data: String data to validate
strict: Whether to use strict validation (overrides config)
context: Additional context for validation
allow_partial: Whether to allow partial validation (bool or 'off'/'on'/'trailing-strings')
by_alias: Whether to use field aliases when validating
by_name: Whether to use field names when validating
Returns:
The validated Python object
Raises:
ValidationError: If validation fails
"""
def validate_assignment(self, obj, field_name, field_value, *, strict=None, from_attributes=None, context=None, by_alias=None, by_name=None):
"""
Validate an assignment to a field on a model.
Args:
obj: The model instance being assigned to
field_name: The name of the field to validate assignment for
field_value: The value to assign to the field
strict: Whether to use strict validation (overrides config)
from_attributes: Whether to extract values from object attributes
context: Additional context for validation
by_alias: Whether to use field aliases when validating
by_name: Whether to use field names when validating
Returns:
Either the model dict or a tuple of (model_data, model_extra, fields_set)
Raises:
ValidationError: If validation fails
"""
def get_default_value(self, *, strict=None, context=None):
"""
Get the default value for the schema, including running default value validation.
Args:
strict: Whether to validate the default value in strict mode
context: Additional context for validation
Returns:
None if the schema has no default value, otherwise a Some containing the default
Raises:
ValidationError: If validation fails
"""
@property
def title(self) -> str:
"""The title of the schema."""The primary serialization class that converts validated data to various output formats including Python dictionaries, JSON, and custom formats.
class SchemaSerializer:
def __init__(self, schema: CoreSchema, config: CoreConfig = None):
"""
Create a new schema serializer.
Args:
schema: The serialization schema to use
config: Optional configuration for serialization behavior
"""
def to_python(self, value, *, mode=None, include=None, exclude=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, context=None):
"""
Serialize to Python objects (dicts, lists, etc.).
Args:
value: The value to serialize
mode: Serialization mode ('python' or 'json'), defaults to 'python'
include: Set of fields to include, if None all fields are included
exclude: Set of fields to exclude, if None no fields are excluded
by_alias: Whether to use field aliases
exclude_unset: Whether to exclude unset fields
exclude_defaults: Whether to exclude default values
exclude_none: Whether to exclude None values
exclude_computed_fields: Whether to exclude computed fields
round_trip: Whether to preserve exact types for round-trip compatibility
warnings: How to handle invalid fields (bool or 'none'/'warn'/'error')
fallback: Fallback function for non-serializable values
serialize_as_any: Whether to serialize unknown types as Any
context: Additional context for serialization
Returns:
Python objects (dict, list, etc.)
"""
def to_json(self, value, *, indent=None, ensure_ascii=False, include=None, exclude=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, context=None) -> bytes:
"""
Serialize to JSON bytes.
Args:
value: The value to serialize
indent: JSON indentation (None for compact, int for spaces)
ensure_ascii: If True, all non-ASCII characters are escaped
include: Set of fields to include, if None all fields are included
exclude: Set of fields to exclude, if None no fields are excluded
by_alias: Whether to use field aliases
exclude_unset: Whether to exclude unset fields
exclude_defaults: Whether to exclude default values
exclude_none: Whether to exclude None values
exclude_computed_fields: Whether to exclude computed fields
round_trip: Whether to preserve exact types for round-trip compatibility
warnings: How to handle invalid fields (bool or 'none'/'warn'/'error')
fallback: Fallback function for non-serializable values
serialize_as_any: Whether to serialize unknown types as Any
context: Additional context for serialization
Returns:
JSON as bytes
"""
@property
def serializer(self):
"""Access to the underlying serializer implementation."""from pydantic_core import SchemaValidator, ValidationError
from pydantic_core.core_schema import str_schema, int_schema, dict_schema
# Create a schema for a person
person_schema = dict_schema({
'name': str_schema(min_length=1, max_length=100),
'age': int_schema(ge=0, le=150),
'email': str_schema()
})
# Create validator
validator = SchemaValidator(person_schema)
# Validate valid data
valid_person = {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
result = validator.validate_python(valid_person)
print(result) # {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
# Validate JSON
json_data = '{"name": "Bob", "age": 25, "email": "bob@example.com"}'
result = validator.validate_json(json_data)
print(result) # {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}from pydantic_core import SchemaSerializer
from pydantic_core.core_schema import dict_schema, str_schema, int_schema
# Create schema and serializer
schema = dict_schema({
'name': str_schema(),
'age': int_schema(),
'active': bool_schema()
})
serializer = SchemaSerializer(schema)
# Data to serialize
data = {'name': 'Charlie', 'age': 35, 'active': True}
# Serialize to Python dict
python_result = serializer.to_python(data)
print(python_result) # {'name': 'Charlie', 'age': 35, 'active': True}
# Serialize to JSON
json_result = serializer.to_json(data)
print(json_result) # b'{"name":"Charlie","age":35,"active":true}'
# Serialize with formatting
formatted_json = serializer.to_json(data, indent=2)
print(formatted_json.decode())
# {
# "name": "Charlie",
# "age": 35,
# "active": true
# }from pydantic_core import SchemaValidator
from pydantic_core.core_schema import CoreConfig, str_schema, dict_schema
# Create configuration
config = CoreConfig(
strict=True,
str_strip_whitespace=True,
str_to_lower=True
)
# Create schema with config
schema = dict_schema({
'username': str_schema(min_length=3),
'password': str_schema(min_length=8)
})
validator = SchemaValidator(schema, config)
# This will strip whitespace and convert to lowercase
data = {'username': ' ALICE ', 'password': 'secretpassword'}
result = validator.validate_python(data)
print(result) # {'username': 'alice', 'password': 'secretpassword'}from pydantic_core import SchemaValidator, ValidationError
from pydantic_core.core_schema import str_schema, int_schema, dict_schema
schema = dict_schema({
'name': str_schema(min_length=2),
'age': int_schema(ge=0, le=120)
})
validator = SchemaValidator(schema)
try:
# Invalid data
invalid_data = {'name': 'A', 'age': 150} # name too short, age too high
validator.validate_python(invalid_data)
except ValidationError as e:
print(f"Validation failed with {e.error_count()} errors:")
for error in e.errors():
print(f" {error['loc']}: {error['msg']}")
# Output:
# Validation failed with 2 errors:
# ('name',): String should have at least 2 characters
# ('age',): Input should be less than or equal to 120Install with Tessl CLI
npx tessl i tessl/pypi-pydantic-core