python - numpy.ndarray 的类型提示/注释 (PEP 484)

标签 python python-3.x numpy type-hinting python-typing

有没有人为特定的 numpy.ndarray 实现类型提示类?

现在,我正在使用 typing.Any ,但最好有更具体的内容。

例如,如果 NumPy 人们添加了 type alias为他们array_like对象类。更好的是,通过 dtype 实现支持级别,以便支持其他对象,以及 ufunc .

最佳答案

Numpy 1.21 包含一个具有 NDArray 泛型类型的 numpy.typing 模块。

<小时/>
来自Numpy 1.21 docs :
numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

A generic version of np.ndarray[Any, np.dtype[+ScalarType]].

Can be used during runtime for typing arrays with a given dtype and unspecified shape.

Examples:

>>> import numpy as np
>>> import numpy.typing as npt

>>> print(npt.NDArray)
numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

>>> print(npt.NDArray[np.float64])
numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]

>>> NDArrayInt = npt.NDArray[np.int_]
>>> a: NDArrayInt = np.arange(10)

>>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
...     return np.array(a)

截至 2022 年 9 月 5 日,对形状的支持仍在进行中,根据 numpy/numpy#16544 .

关于python - numpy.ndarray 的类型提示/注释 (PEP 484),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673895/

相关文章:

python - 无法使用 Celery 安排和重新安排帖子

python - 通过 QtCore.SignalMapper 调用槽

python - 多重继承中基类的顺序和 super() 的使用

python-3.x - 如何总结 Pandas 数据框中每行的缺失值

python - 处理缺失数据

python - scipy LU分解置换矩阵

python - 观看网络目录时出现 pywintypes.error

python - 从存储帐户安装私有(private) python 轮

python - 我可以在 pandas 中获得一个额外的标题作为所有列顶部的名称吗

python - numpy中的对角线堆叠?