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!
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:
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.
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.
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 .)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With