问题
I would like a function to include a type hint for NumPy ndarray
's alongside with its dtype
.
With lists, for example, one could do the following...
def foo(bar: List[int]):
...
...in order to give a type hint that bar
has to be list
consisting of int
's.
Unfortunately, this syntax throws exceptions for NumPy ndarray
:
def foo(bar: np.ndarray[np.bool]):
...
> np.ndarray[np.bool]) (...) TypeError: 'type' object is not subscriptable
Is it possible to give dtype
-specific type hints for np.ndarray
?
回答1:
To the best of my knowledge it's not possible yet to specify dtype
in numpy array type hints in function signatures. It is planned to be implemented at some point in the future. See numpy GitHub issue #7370 and numpy-stubs GitHub for more details on the current development status.
回答2:
You could check out nptyping:
from nptyping import Array
def foo(bar: Array[np.bool]):
...
Or you could just use strings for type hints:
def foo(bar: 'np.ndarray[np.bool]'):
...
来源:https://stackoverflow.com/questions/54503964/type-hint-for-numpy-ndarray-dtype