numpydantic¶
Top-level API contents
- class NDArray(val: NDArrayType)[source]
Constrained array type allowing npytyping syntax for dtype and shape validation and serialization.
This class is not intended to be instantiable, and support for static type checking is limited, it implements the
__get_pydantic_core_schema__method to invoke the relevant interface for validation and serialization.It is callable, however, which validates and attempts to coerce input to a supported array type. There is no such thing as an “NDArray instance,” but one can think of it as a validating passthrough callable.
References
- shape
Tuple of array dimensions.
The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.
Warning
Setting
arr.shapeis discouraged and may be deprecated in the future. Using ndarray.reshape is the preferred approach.Examples
>>> import numpy as np >>> x = np.array([1, 2, 3, 4]) >>> x.shape (4,) >>> y = np.zeros((2, 3, 4)) >>> y.shape (2, 3, 4) >>> y.shape = (3, 8) >>> y array([[ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> y.shape = (3, 6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot reshape array of size 24 into shape (3,6) >>> np.zeros((4,2))[::2].shape = (-1,) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Incompatible shape for in-place modification. Use `.reshape()` to make a copy with the desired shape.
See also
numpy.shapeEquivalent getter function.
numpy.reshapeFunction similar to setting
shape.ndarray.reshapeMethod similar to setting
shape.
- dtype
Data-type of the array’s elements.
Warning
Setting
arr.dtypeis discouraged and may be deprecated in the future. Setting will replace thedtypewithout modifying the memory (see also ndarray.view and ndarray.astype).- Parameters:
None
- Returns:
d
- Return type:
numpy dtype object
See also
ndarray.astypeCast the values contained in the array to a new data-type.
ndarray.viewCreate a view of the same data but a different data-type.
Examples
>>> import numpy as np >>> x = np.arange(4).reshape((2, 2)) >>> x array([[0, 1], [2, 3]]) >>> x.dtype dtype('int64') # may vary (OS, bitness) >>> isinstance(x.dtype, np.dtype) True
- NDArraySchema(shape: type[~numpydantic.validation.shape.Shape[*, ...]] | ~numpydantic.validation.shape.Shape[*, ...] | str | tuple = Shape['*, ...'], dtype: str | type | ~typing.Any | ~numpy.generic = typing.Any) GetPydanticSchema[source]
Specify shape and dtype constraints in an
typing.Annotatedtype.In addition to validating dtype and shape constraints, the
typeof the array will also be validated - i.e. if the annotation is for anumpy.ndarray, adask.array.Arraywill be rejected even if it has the correct shape and dtype.Examples
>>> from typing import Annotated as A >>> from numpydantic import Shape, NDArraySchema >>> import numpy as np >>> from pydantic import BaseModel
>>> class MyModel(BaseModel): >>> array: A[np.ndarray, NDArraySchema(Shape(3, 3), np.uint8)]
or, without Shape
>>> class MyOtherModel(BaseModel): >>> array: A[np.ndarray, NDArraySchema((3, 3), np.uint8)]
Valid:
>>> MyModel(array=np.ones((3, 3), dtype=np.uint8))
Not valid:
>>> MyModel(array=dask.array.ones((3, 3), dtype=np.uint8))
- Parameters:
Returns:
- class Shape(*args: str | int)[source]
A container for shape expressions that describe the shape of an multi dimensional array.
Simple example:
>>> Shape['2, 2'] Shape['2, 2']
A Shape can be compared to a typing.Literal. You can use Literals in NDArray as well.
>>> from typing import Literal
>>> Shape['2, 2'] == Literal['2, 2'] True
A Shape can be constructed by calling for type checker compatibility
>>> Shape['2, 2'] == Shape('2, 2')
And its arguments can be pased as
args, with ints and strings as appropriate>>> Shape(2, 2, "...") == Shape("2, 2, ...")
Create a new Shape as a callable