Type hint for NumPy ndarray dtype? Type hint for NumPy ndarray dtype? numpy numpy

Type hint for NumPy ndarray dtype?


You could check out nptyping:

from nptyping import NDArray, Booldef foo(bar: NDArray[Bool]):   ...

Or you could just use strings for type hints:

def foo(bar: 'np.ndarray[np.bool]'):   ...


Check out data-science-types package.

pip install data-science-types

MyPy now has access to Numpy, Pandas, and Matplotlib stubs.Allows scenarios like:

# program.pyimport numpy as npimport pandas as pdarr1: np.ndarray[np.int64] = np.array([3, 7, 39, -3])  # OKarr2: np.ndarray[np.int32] = np.array([3, 7, 39, -3])  # Type errordf: pd.DataFrame = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) # OKdf1: pd.DataFrame = pd.Series([1,2,3]) # error: Incompatible types in assignment (expression has type "Series[int]", variable has type "DataFrame")

Use mypy like normal.

$ mypy program.py

Usage with function-parameters

def f(df: pd.DataFrame):    return df.head()if __name__ == "__main__":    x = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6]})    print(f(x))$ mypy program.py> Success: no issues found in 1 source file


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.