Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy type hints in Python (PEP 484)

Tags:

python

numpy

pep

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!

like image 997
sidou Avatar asked Oct 16 '18 15:10

sidou


People also ask

Does NumPy support type-hinting?

Numpy 1.21 includes some support for type-hinting. Specifically, the numpy.typing module exposes an NDArray generic type. The below description and examples are taken straight from the Numpy 1.21 docs:

Is Pep 484 still in use?

When evaluating this question and answer, pay attention to the date. 484 was a relatively new PEP back then, and code to make use of it for standard Python still in development. But it looks like the links provided are still valid.

What is get_type_hints() in Python?

get_type_hints (), a utility function to retrieve the type hints from a function or method. Given a function or method object, it returns a dict with the same format as __annotations__, but evaluating forward references (which are given as string literals) as expressions in the context of the original function or method definition.

Should type hinting be used for typing variables?

If type hinting proves useful in general, a syntax for typing variables may be provided in a future Python version. ( UPDATE: This syntax was added in Python 3.6 through PEP 526 .)


1 Answers

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.
like image 102
R H Avatar answered Nov 15 '22 17:11

R H