Getting Started
pydantic-core provides the core functionality for Pydantic validation and serialization. It is written in Rust for high performance and is significantly faster than Pydantic V1.
[!NOTE] Most users should not use
pydantic-coredirectly. Instead, use the mainpydanticpackage, which provides a higher-level API and usespydantic-coreinternally.
Prerequisites
- Python: 3.10 or newer.
- Rust: Stable version (only required if building from source).
- uv: Recommended for development and dependency management.
- make: Used for running development commands.
Installation
The easiest way to install pydantic-core is via pip:
pip install pydantic-core
Hello World / Quick Start
pydantic-core uses a schema-based approach to validation. You define a schema as a Python dictionary and use SchemaValidator to validate data against it.
from pydantic_core import SchemaValidator, ValidationError
# Define a schema for a dictionary with specific fields
v = SchemaValidator(
{
'type': 'typed-dict',
'fields': {
'name': {
'type': 'typed-dict-field',
'schema': {'type': 'str'},
},
'age': {
'type': 'typed-dict-field',
'schema': {
'type': 'int',
'ge': 18,
},
},
},
}
)
# Validate Python data
try:
result = v.validate_python({'name': 'Samuel', 'age': 35})
print(result)
# Output: {'name': 'Samuel', 'age': 35}
except ValidationError as e:
print(e)
# pydantic-core can also validate JSON directly for better performance
json_data = '{"name": "Samuel", "age": 35}'
result_json = v.validate_json(json_data)
assert result == result_json
Verify Installation
You can verify that pydantic-core is installed correctly by checking its version:
python -c "import pydantic_core; print(pydantic_core.__version__)"
Other Install Options
Development Setup
If you want to contribute to pydantic-core or build it from source, follow these steps:
-
Clone the repository:
git clone https://github.com/pydantic/pydantic-core.git
cd pydantic-core -
Install dependencies and build the development version using
make:make install -
Run tests to ensure everything is working:
make test
Next Steps
- Schema Definitions: See pydantic_core.core_schema for a full list of available schema types and configuration options.
- Usage Examples: Explore the tests/ directory for comprehensive examples of validators and serializers.
- Type Hints: Refer to pydantic_core for the Python API type definitions.
Troubleshooting
Building from Source
If you encounter issues while building from source (e.g., during pip install on an unsupported platform), ensure you have the latest version of the Rust toolchain installed:
rustup update stable
Performance Profiling
On Linux, you can profile the code using flamegraph:
cargo install flamegraph
make build-profiling
flamegraph -- pytest tests/benchmarks/test_micro_benchmarks.py