0

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

5
  • You missed the line in the linked answer about the matching dtype to the factory on the right side.. mypy doesn't check that np.array([...]) produces the annotated dtype. That's a dynamic result, one that a static type analyzer can't handle. mypy handles [1, 2, 3] because that's easy check as a list of ints. [0.1, 0.2, 0.3] is a list of floats, which is then passed to np.array factory, which in turn (with complex numpy code), produces an array. Commented Mar 8, 2023 at 16:48
  • Please upgrade mypy if possible - 1.1.0 was released recently, and since 0.910 they added a noticeable number of bugfixes and features. npt.NDArray[np.int64] is a proper annotations, do you have plugin enabled? Commented Mar 8, 2023 at 16:49
  • @hpaulj thank you for your reply! Do you mean that it is not possible to check the types of a numpy array as we do with types in a list? Commented Mar 22, 2023 at 9:09
  • @SUTerliakov thank you for your reply! I will update to the new release. What exactly do you mean with the plugin? Commented Mar 22, 2023 at 9:10
  • This one Commented Mar 22, 2023 at 10:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.