ndarray

Extension of nptyping NDArray for pydantic that allows for JSON-Schema serialization

Note

This module should only have the NDArray class in it, because the type stub ndarray.pyi is only created for NDArray . Otherwise, type checkers will complain about using any helper functions elsewhere - those all belong in numpydantic.schema .

Keeping with nptyping’s style, NDArrayMeta is in this module even if it’s excluded from the type stub.

class NDArrayMeta(name, bases, namespace, /, **kwargs)[source]

Metaclass to provide class-level methods to NDArray protocol without suggesting they are part of the protocol definition.

__call__(val: NDArrayType) NDArrayType[source]

Call ndarray as a validator function

__instancecheck__(instance: Any)[source]

Extended type checking that determines whether

  1. the type of the given instance is one of those in

    Interface.input_types()

but also

  1. it satisfies the constraints set on the NDArray annotation

Parameters:

instance (typing.Any) – Thing to check!

Returns:

True if matches constraints, False otherwise.

Return type:

bool

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.shape is 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.shape

Equivalent getter function.

numpy.reshape

Function similar to setting shape.

ndarray.reshape

Method similar to setting shape.

dtype

Data-type of the array’s elements.

Warning

Setting arr.dtype is discouraged and may be deprecated in the future. Setting will replace the dtype without modifying the memory (see also ndarray.view and ndarray.astype).

Parameters:

None

Returns:

d

Return type:

numpy dtype object

See also

ndarray.astype

Cast the values contained in the array to a new data-type.

ndarray.view

Create a view of the same data but a different data-type.

numpy.dtype

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