python-3.x - 使用 mypy 对 NumPy ndarray 进行特定类型注释

标签 python-3.x numpy numpy-ndarray mypy

NumPy 1.20 中添加了对类型注释的支持。
我试图弄清楚如何告诉 mypy 一个数组填充了特定类型的元素,注释 np.ndarray[np.dcomplex]给出 mypy 错误 "ndarray" expects no type arguments, but 1 given .
编辑:这个问题不同于 Type hinting / annotation (PEP 484) for numpy.ndarray因为这个问题是在 4 年前提出的,当时没有任何官方支持类型提示。我问的是什么是官方的方法,现在numpy 1.20实际上支持类型提示。文档位于 https://numpy.org/doc/stable/reference/typing.html#module-numpy.typing那里的最高答案似乎只是说你不应该用类型提示做的事情,而不是解释你应该做什么。

最佳答案

您要找的是numpy.typing.NDArray类(class):https://numpy.org/doc/stable/reference/typing.html#numpy.typing.NDArraynumpy.typing.NDArray[A]numpy.ndarray[Any, numpy.dtype[A]] 的别名:

import numpy as np
import numpy.typing as npt

a: npt.NDArray[np.complex64] = np.zeros((3, 3), dtype=np.complex64)
# reveal_type(a)  # -> numpy.ndarray[Any, numpy.dtype[numpy.complexfloating[numpy.typing._32Bit, numpy.typing._32Bit]]]
print(a)
打印
[[0.+0.j 0.+0.j 0.+0.j]
 [0.+0.j 0.+0.j 0.+0.j]
 [0.+0.j 0.+0.j 0.+0.j]]
请注意,即使您注释了 anpt.NDArray[np.complex64] ,你仍然需要确保你通过了匹配的 dtype到右边的工厂。
a: npt.NDArray[np.complex64] = np.zeros((3, 3), dtype=np.float32)
同样通过 mypy 检查。

关于python-3.x - 使用 mypy 对 NumPy ndarray 进行特定类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66349242/

相关文章:

python - 使用某些投影时 Basemap.contour() 出现 IndexError

python - 类型错误 : unsupported operand type(s) for/: 'Image' and 'int'

python-3.x - Pandas 的 str.strip 性能

python - 用 0 和 1 填充的 numpy 二维数组的所有组合

python - 当值超出范围时,在二维数组中显示错误的轴

python - Python3.3需要watcher

python - 读/写 NumPy 结构化数组非常慢,线性大小慢

python - 在 2d numpy 数组的给定索引之间填充值

python - 在 Pandas 中添加日期

python - 值错误: could not convert string to float: 'lisans' in Python