Numpy type hints in Python (PEP 484)

这一生的挚爱 提交于 2019-12-10 12:58:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!