Numpy type hint memorandum (NDArray)

I'm a little addicted to the type hints and type checks of Numpy, so I'll leave it as a memorandum.

This time I'm using a library for typing for numpy called nptyping. Repository: GitHub --ramonhagenaars / nptyping

When vector

The bottom two are True even if the element is not ʻint. ** (ʻAny is imported from the standard library typing) **

vec = np.array([1, 2, 3], int)
isinstance(vec, NDArray[3, int]) # True
isinstance(vec, NDArray[(3,), int]) # True
isinstance(vec, NDArray[(3, ...), int]) # True
isinstance(vec, NDArray[(3,), Any]) # True
isinstance(vec, NDArray[3]) # True

When in a line

At the top is the $ (any) \ times3 $ matrix. The bottom two are True even if they are not ʻint. ** (ʻAny is imported from the standard library typing) **

mat = np.array([[1, 2, 3], [4, 5, 6]], int)
isinstance(mat, NDArray[(Any, 3), int]) # True
isinstance(mat, NDArray[(2, 3), int]) # True
isinstance(mat, NDArray[2, 3]) # True
isinstance(mat, NDArray[(2, 3), Any]) # True

Recommended Posts

Numpy type hint memorandum (NDArray)
RAID type memorandum
numpy memorandum 1 / np.pad
[Numpy] Shuffle ndarray
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]