问题
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:
Check out nptyping. It offers type hints for numpy arrays.
In your case, you would end up with:
import numpy as np
from nptyping import Array
def foo(array: Array[np.float64]) -> str:
...
You can check your instances as well:
arr = np.array([[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0]])
isinstance(arr, Array[np.float64, 3, 2]) # True
来源:https://stackoverflow.com/questions/52839427/numpy-type-hints-in-python-pep-484