Pydantic NumPy
raw JSON → 9.0.1 verified Mon Apr 27 auth: no python
Integrate NumPy arrays into Pydantic models with type validation, shape constraints, and dtype checking. Currently version 9.0.1 (requires Python >=3.11, <3.15). Active development with frequent breaking changes across major versions.
pip install pydantic-numpy Common errors
error ImportError: cannot import name 'NDArray' from 'pydantic_numpy.typing' ↓
cause Import path changed in v8. NDArray is now in the root package.
fix
Use 'from pydantic_numpy import NDArray'
error TypeError: 'tuple' object is not callable ↓
cause Misusing numpy_array syntax: numpy_array(shape=(3,4)) where shape is a tuple but used incorrectly as a function.
fix
In field annotation, use 'field: numpy_array(shape=(3,4))' not 'field = numpy_array(...)'.
error pydantic.errors.PydanticSchemaGenerationError: Unable to generate schema for <class 'numpy.ndarray'> ↓
cause Using bare numpy.ndarray as a field type instead of numpy_array.
fix
Use the provided numpy_array type in field annotation.
Warnings
breaking Breaking changes between major versions are common. For example, v8 changed the import path of NDArray from pydantic_numpy.typing to pydantic_numpy root. Always check the changelog when upgrading. ↓
fix Update imports to 'from pydantic_numpy import NDArray' and review the migration guide.
gotcha numpy_array is not a function; it's a special form used in type annotations. Attempting to call numpy_array(...) as a function will raise an error. ↓
fix Use 'field: numpy_array(...)' inside class definition, not as a function call.
gotcha Shape validation uses tuples; incorrect shape syntax (e.g., using lists) may fail silently or raise unexpected errors. ↓
fix Always provide shape as a tuple: shape=(3, 4) not shape=[3, 4].
deprecated Some older parameter names like 'strict' have been deprecated in favor of 'strict_mode' (or similar) in recent versions. ↓
fix Check the latest documentation for current parameter names.
Imports
- NDArray wrong
from pydantic_numpy.typing import NDArraycorrectfrom pydantic_numpy import NDArray - NumpyModel wrong
from pydantic_numpy.model import NumpyModelcorrectfrom pydantic_numpy import NumpyModel - numpy_array
from pydantic_numpy import numpy_array
Quickstart
from pydantic_numpy import NumpyModel, numpy_array
class MyModel(NumpyModel):
data: numpy_array(shape=(3, 4), dtype=float)
array_instance = MyModel(data=[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]])
print(array_instance.data)