Pydantic Core Internal Architecture
The architecture of pydantic-core is centered around a high-performance Rust core that provides validation and serialization logic for Python.
The system is divided into two main layers:
- Python Interface: This layer defines the CoreSchema, which is a structured dictionary (TypedDict) that describes how data should be validated and serialized. The
core_schemamodule provides helper functions to build these schemas. - Rust Core: The
_pydantic_coreRust extension implements the heavy lifting. It takes aCoreSchemafrom Python and compiles it into a tree of Rust-based validators or serializers.
Key components include:
- SchemaValidator: The primary entry point for validation. It takes a schema and provides methods like
validate_pythonandvalidate_json. Internally, it uses aCombinedValidatorto dispatch to specific type validators (e.g.,StrValidator,IntValidator). - SchemaSerializer: The primary entry point for serialization. It converts Python objects into JSON or other Python-compatible formats based on the schema.
- Input Trait: A crucial abstraction in the Rust core that allows the same validation logic to be applied to different input formats (Python objects, JSON bytes, etc.) without unnecessary conversion.
- CoreSchema: The "contract" between Python and Rust, defining the structure and constraints of the data.
Key Architectural Findings:
- The
pydantic_corePython package acts as a thin wrapper around the_pydantic_coreRust extension. core_schema.pydefines theCoreSchematype, which is the primary configuration format passed from Python to Rust.SchemaValidatorandSchemaSerializerare implemented in Rust and exposed to Python via PyO3.- The Rust core uses an
Inputtrait to abstract over different data sources (Python objects, JSON), enabling high-performance validation without intermediate Python object creation for JSON. - Validation and serialization logic is modularized into specific Rust modules (e.g.,
src/validators/string.rs,src/serializers/type_serializers/dict.rs).
Loading diagram...