18
votes

I would like to add type hints to a method that takes a numpy array as an input, and returns a string. This numpy array contains floats so I tried:

import numpy as np
def foo(array: np.ndarray[np.float64]) -> str:

But it will not work due to a TypeError: 'type' object is not subscriptable.

I found this but could not follow the discussions!

1
It looks like that link is an experimental package that is still in development. Have you looked at the built-in typing library? - G. Anderson
stackoverflow.com/questions/35673895/… is an answer I gave several years back. 484 type hints were experimental then, and may still be. And stackoverflow.com/questions/38005633/… - hpaulj
There is now an open issue in the numpy github repository regarding type hinting / annotation for numpy types. - Jasha

1 Answers

12
votes

Check out nptyping. It offers type hints for numpy arrays.

In your case, you would end up with:

from nptyping import NDArray, Float64

def foo(array: NDArray[Float64]) -> str:
    ...

You can check your instances as well:

import numpy as np
from nptyping import NDArray, Float64

arr = np.array([[1.0, 2.0],
                [3.0, 4.0],
                [5.0, 6.0]])

isinstance(arr, NDArray[(3, 2), Float64])  # True.

# Or if you don't want to check the dimensions and their sizes:
isinstance(arr, NDArray[Float64])  # Also True.