I would like to add annotation to my Numpy arrays so I can use the Mypy library to type check, in a similar way as I do, for example, with lists:
l: list[int] = [0,1, 2]
(correct according to Mypy)
l: list[int] = [0.0,0.1, 0.2]
(Mypy throws an error)
However, if I use a similar method with Numpy arrays, Mypy never throws errors:
import numpy.typing as npt
a: [npt.NDArray[np.int64] = np.array([0.1, 0.2, 0.3])
(no error according to Mypy)
I can even do things like this:
a[0] = 2.0
and Mypy does not throw errors.
I based the Mypy typing for Numpy arrays on this post: Specific type annotation for NumPy ndarray using mypy
It seems that I’m not using the correct typing for Numpy, so I experimented with different ways of adding typing for Numpy arrays:
a: np.ndarray[Any, np.int64] = np.array([0,1,0])
(Mypy returns that the Type argument must be a subtype of numpy.dtype[Any] and that there are incompatible types in the assignment)
a: np.ndarray[Any, np.int64] = np.array([0,1,0], dtype= np.int64)
(Mypy returns that the Type argument must be a subtype of numpy.dtype[Any] and that there are incompatible types in the assignment)
Can someone explain what the correct way of adding type annotations to numpy arrays is?
I’m using mypy version 0.910 and numpy version 1.23.1