Registry / serialization / numpydantic

numpydantic

JSON →
library1.9.1pypypi✓ verified 85d ago

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.

pip install numpydantic
INSTALL
IMPORT
SIG · NUMPYDANTIC
N
numpydantic
serializationpythonv1.9.1
Install
5.3s avg
Import
786ms
Disk
100MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.9.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.788s · 100.2MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 5.3s · import 0.785s · 96MB
100MB installed
● package 100MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

NDArray
from numpydantic import NDArray

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}")
Debug
Known issues
gotchaWhen serializing a Pydantic model containing `NDArray` fields (e.g., using `model_dump_json`), NumPy arrays are, by default, converted into standard Python lists (list of lists). For very large arrays, this can be extremely inefficient, consume significant memory, and result in large JSON payloads.
fix
For efficient serialization of large arrays, consider implementing custom serializers that convert arrays to a more compact format (e.g., Base64 encoded bytes, or leveraging a binary format like Parquet or HDF5) or storing only metadata (shape, dtype) and loading data separately. Pydantic's `model_dump` `mode='json'` or custom JSON encoders can be used.
affects: All versions
gotcha`numpydantic` heavily relies on `typing.Annotated` for specifying array shape and data type constraints. Incorrectly structuring these annotations (e.g., providing a plain tuple instead of `NDArray[(shape_tuple), (dtype_string)]`) will lead to validation errors or unexpected behavior.
fix
Always use `Annotated[NDArray[shape_spec, dtype_spec], 'description']`. The `shape_spec` should be a tuple or string (e.g., `(3, 'width')`, `"*"`, `"*,*"`), and `dtype_spec` a string (e.g., `'float'`, `'int64'`, `'uint8'`). Refer to the official `numpydantic` documentation for detailed annotation syntax.
affects: All versions
gotchaWhile `numpydantic` aims for compatibility with both Pydantic v1.x and v2.x, subtle behavioral differences in Pydantic's core validation and serialization mechanisms might exist. For instance, `model.json()` is deprecated in Pydantic v2 in favor of `model.model_dump_json()`.
fix
Always test your models thoroughly after Pydantic version upgrades. Use `model.model_dump_json()` for serialization in Pydantic v2. Refer to Pydantic's official migration guides for comprehensive changes between major versions.
affects: All versions, especially when migrating Pydantic versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'numpydantic'
The numpydantic library is not installed in the current Python environment.
fix
pip install numpydantic
pydantic.ValidationError: Input should be a valid NumPy array
A non-NumPy array type (e.g., a Python list or tuple) was provided where a numpydantic.NumpyArray type was expected in the Pydantic model.
fix
Convert the input data to a NumPy array using `numpy.array()` before passing it to the Pydantic model.
pydantic.ValidationError: N-dimensional array has wrong number of dimensions
The NumPy array provided to the Pydantic model has a different number of dimensions (rank) than specified in the numpydantic.NumpyArray type hint's shape.
fix
Ensure the input NumPy array has the correct number of dimensions (e.g., 2 for a matrix, 1 for a vector) that matches the numpydantic.NumpyArray definition, for example, `NumpyArray[float, (2, 3)]` expects a 2D array.
Upgrade
Version history
1.9.1latest on PyPI · released Jun 8, 2026
Audit
Dependencies
pydanticrequiredCore dependency for model definition and validation, supports >=1.8,<3.0
numpyrequiredRequired for array manipulation and `NDArray` type, supports >=1.20
Agent activity
5 hits · last 30 days
node
4
Amazon
1
Resources
numpydantic — pip install numpydantic · libregistry