pydantic-core

2.44.0 · active · verified Sat Mar 28

pydantic-core is the Rust-powered engine that underpins all validation and serialization in Pydantic V2+. Written in Rust via PyO3, it exposes SchemaValidator, SchemaSerializer, ValidationError, and the core_schema builder API to Python. End-users should interact with it only through the higher-level `pydantic` package; direct use is intended for library authors implementing custom types via __get_pydantic_core_schema__. The library releases in lockstep with pydantic — each pydantic-core version is pinned to exactly one pydantic version and does not follow SemVer independently. Current version is 2.44.0, released frequently (multiple times per month) alongside pydantic.

Warnings

Install

Imports

Quickstart

Directly construct and use a SchemaValidator with core_schema helpers. Most users should use the higher-level pydantic.BaseModel instead; this API is for library authors or performance-critical custom validation pipelines.

from pydantic_core import SchemaValidator, ValidationError, core_schema

# Build a schema using the core_schema helpers
schema = core_schema.typed_dict_schema(
    {
        'name': core_schema.typed_dict_field(core_schema.str_schema()),
        'age': core_schema.typed_dict_field(
            core_schema.int_schema(ge=18)
        ),
        'is_developer': core_schema.typed_dict_field(
            core_schema.with_default_schema(
                core_schema.bool_schema(), default=True
            ),
            required=False,
        ),
    }
)

v = SchemaValidator(schema)

# Validate a Python dict
result = v.validate_python({'name': 'Alice', 'age': 30})
print(result)  # {'name': 'Alice', 'age': 30, 'is_developer': True}

# Validate JSON bytes directly (faster than json.loads + validate_python)
result_json = v.validate_json('{"name": "Bob", "age": 25}')
print(result_json)

# Catch validation errors
try:
    v.validate_python({'name': 'Eve', 'age': 15})
except ValidationError as e:
    print(e)
    # 1 validation error for typed-dict
    # age
    #   Input should be greater than or equal to 18 [type=greater_than_equal, ...]

view raw JSON →