Core functionality for Pydantic validation and serialization
npx @tessl/cli install tessl/pypi-pydantic-core@2.39.0Pydantic Core is a high-performance validation and serialization library implemented in Rust with Python bindings. It provides the foundational validation engine for Pydantic V2, offering approximately 17x performance improvements over pure Python implementations. The library handles schema-based validation, JSON parsing and serialization, error handling with detailed validation messages, and support for complex data types.
pip install pydantic-coreimport pydantic_coreMain classes and functions:
from pydantic_core import (
SchemaValidator,
SchemaSerializer,
ValidationError,
from_json,
to_json,
to_jsonable_python
)Schema building functions:
from pydantic_core.core_schema import (
CoreConfig,
str_schema,
int_schema,
dict_schema,
list_schema,
model_schema
)from pydantic_core import SchemaValidator, ValidationError
from pydantic_core.core_schema import str_schema, int_schema, dict_schema
# Define a schema for user data
user_schema = dict_schema({
'name': str_schema(min_length=1),
'age': int_schema(ge=0, le=120),
'email': str_schema()
})
# Create a validator
validator = SchemaValidator(user_schema)
# Validate valid data
valid_data = {'name': 'John', 'age': 30, 'email': 'john@example.com'}
result = validator.validate_python(valid_data)
print(result) # {'name': 'John', 'age': 30, 'email': 'john@example.com'}
# Handle validation errors
try:
invalid_data = {'name': '', 'age': -5, 'email': 'invalid'}
validator.validate_python(invalid_data)
except ValidationError as e:
print(e.error_count()) # Number of errors
for error in e.errors():
print(f"Field: {error['loc']}, Error: {error['msg']}")Pydantic Core is built around several key concepts:
The Rust implementation provides the performance-critical validation logic while maintaining a Python-friendly API through PyO3 bindings.
Main classes for validating data against schemas and serializing validated data to various output formats including JSON, Python dictionaries, and custom formats.
class SchemaValidator:
def __init__(self, schema: CoreSchema, config: CoreConfig = None): ...
def validate_python(self, value, *, strict=None, from_attributes=None, context=None): ...
def validate_json(self, json_data, *, strict=None, context=None): ...
def validate_strings(self, str_data, *, strict=None, context=None): ...
class SchemaSerializer:
def __init__(self, schema: CoreSchema, config: CoreConfig = None): ...
def to_python(self, value, *, mode='python', by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False): ...
def to_json(self, value, *, indent=None, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False): ...Comprehensive set of functions for building validation schemas for all Python data types, from basic types like strings and integers to complex structures like models and typed dictionaries.
def str_schema(*, min_length=None, max_length=None, pattern=None, strip_whitespace=False, to_lower=False, to_upper=False): ...
def int_schema(*, gt=None, ge=None, lt=None, le=None, multiple_of=None): ...
def dict_schema(keys_schema=None, values_schema=None, *, min_length=None, max_length=None): ...
def list_schema(items_schema, *, min_length=None, max_length=None): ...
def model_schema(cls_name: str, schema: dict, *, model_name=None, config=None, custom_init=None, root_model=False, post_init=None, ref=None, serialization=None, extra_validator=None): ...High-performance JSON parsing and serialization functions with extensive configuration options for handling edge cases, infinity/NaN values, and custom serialization formats.
def from_json(data, *, allow_inf_nan=True, cache_strings='all', allow_partial='off'): ...
def to_json(obj, *, indent=None, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False) -> bytes: ...
def to_jsonable_python(obj, *, fallback=None, serialize_as_any=False, when_used='json'): ...
# Utility functions
def list_all_errors() -> list[ErrorTypeInfo]: ...
# Build information
__version__: str
build_profile: str
build_info: str
_recursion_limit: intComprehensive error handling system with detailed error information, location tracking, and support for custom error messages and error type definitions.
class ValidationError(ValueError):
def errors(self) -> list[ErrorDetails]: ...
def error_count(self) -> int: ...
def __str__(self) -> str: ...
class PydanticCustomError(ValueError):
def __init__(self, error_type: str, message_template: str, context: dict = None): ...
class PydanticKnownError(ValueError):
def __init__(self, error_type: ErrorType, context: dict = None): ...Specialized validation and handling for URLs and multi-host URLs commonly used in database connections and network configurations.
class Url:
scheme: str
username: str | None
password: str | None
host: str | None
port: int | None
path: str | None
query: str | None
fragment: str | None
class MultiHostUrl:
scheme: str
username: str | None
password: str | None
hosts: list[MultiHostHost]
path: str | None
query: str | None
fragment: str | NoneSentinel values, utility classes, and helper functions for advanced validation scenarios and edge case handling.
# Sentinel values
PydanticUndefined: PydanticUndefinedType
MISSING: Sentinel
UNSET: Sentinel # Alias for MISSING
# Utility classes
class Some:
def __init__(self, value): ...
class ArgsKwargs:
def __init__(self, args: tuple, kwargs: dict): ...
# Marker classes
class PydanticOmit: ...
class PydanticUseDefault: ...# Core type aliases
CoreSchema = Union[AnySchema, NoneSchema, BoolSchema, IntSchema, FloatSchema, StrSchema, BytesSchema, DateSchema, TimeSchema, DatetimeSchema, TimedeltaSchema, LiteralSchema, EnumSchema, IsInstanceSchema, CallableSchema, ListSchema, TupleSchema, SetSchema, FrozensetSchema, GeneratorSchema, DictSchema, AfterValidatorFunctionSchema, BeforeValidatorFunctionSchema, WrapValidatorFunctionSchema, PlainValidatorFunctionSchema, WithInfoAfterValidatorFunctionSchema, WithInfoBeforeValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema, WithInfoPlainValidatorFunctionSchema, ChainSchema, LaxOrStrictSchema, UnionSchema, TaggedUnionSchema, ModelSchema, ModelFieldsSchema, DataclassSchema, TypedDictSchema, CallableSchema, ArgumentsSchema, CustomErrorSchema, JsonSchema, UrlSchema, MultiHostUrlSchema, DecimalSchema, UuidSchema, NoInfoSchema, CustomSchema, NullableSchema, DefaultSchema, WithInfoSchema, DefinitionsSchema, DefinitionReferenceSchema, ValidatorSchema, SerializerSchema, JsonOrPythonSchema]
CoreSchemaType = Literal[
'any', 'none', 'bool', 'int', 'float', 'str', 'bytes', 'date', 'time',
'datetime', 'timedelta', 'frozenset', 'list', 'dict', 'function',
'generator', 'tuple', 'set', 'is_instance', 'callable', 'literal',
'enum', 'union', 'tagged_union', 'chain', 'model', 'model_fields',
'dataclass', 'typed_dict', 'json', 'url', 'multi_host_url', 'uuid',
'decimal', 'no_info', 'custom', 'arguments', 'nullable', 'default',
'with_info', 'definitions', 'definition_ref', 'validator',
'serializer', 'lax_or_strict', 'json_or_python'
]
# Error and context types
ErrorDetails = TypedDict('ErrorDetails', {
'type': str,
'loc': tuple[int | str, ...],
'msg': str,
'input': Any,
'ctx': NotRequired[dict[str, Any]],
'url': NotRequired[str]
})
InitErrorDetails = TypedDict('InitErrorDetails', {
'type': Union[str, PydanticCustomError],
'loc': NotRequired[tuple[int | str, ...]],
'input': Any,
'ctx': NotRequired[dict[str, Any]]
})
ErrorTypeInfo = TypedDict('ErrorTypeInfo', {
'type': ErrorType,
'message_template_python': str,
'example_message_python': str,
'message_template_json': NotRequired[str],
'example_message_json': NotRequired[str],
'example_context': dict[str, Any] | None
})
MultiHostHost = TypedDict('MultiHostHost', {
'username': str | None,
'password': str | None,
'host': str | None,
'port': int | None
})