Numpydantic

1.8.1 · active · verified Wed Apr 15

Numpydantic provides robust type and shape validation, and serialization capabilities for arbitrary array types (primarily NumPy arrays) within Pydantic models. It enables developers to define strict data contracts for numerical data, integrating seamlessly with Pydantic v1.x and v2.x. The current version is 1.8.1, with a consistent, active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Pydantic model using `numpydantic.NDArray` to enforce specific array shapes and data types. It shows examples of valid model instantiation and how validation errors are caught for incorrect data.

from typing import Annotated
import numpy as np
from pydantic import BaseModel
from numpydantic import NDArray

class MyModel(BaseModel):
    image: Annotated[NDArray[("width", "height"), "uint8"], "Image data"]
    matrix: Annotated[NDArray["*,*", float], "Arbitrary float matrix"]
    vector: Annotated[NDArray[3, int], "3-element integer vector"]

# Example usage:
try:
    model = MyModel(
        image=np.zeros((100, 200), dtype=np.uint8),
        matrix=np.ones((2, 2), dtype=float),
        vector=np.array([1, 2, 3], dtype=int)
    )
    print("Model created successfully:")
    print(model.model_dump_json(indent=2))

    # Example of validation error
    print("\nAttempting invalid data:")
    MyModel(
        image=np.zeros((50, 50), dtype=np.float32), # Wrong dtype
        matrix=np.array([1, 2, 3]), # Wrong dimensions
        vector=np.array([1, 2], dtype=int) # Wrong size
    )
except Exception as e:
    print(f"Caught expected error: {type(e).__name__}: {e}")

view raw JSON →