使用 mypy 的 NumPy ndarray 的特定类型注释
Specific type annotation for NumPy ndarray using mypy
在 NumPy 1.20 中添加了对类型注释的支持。
我试图弄清楚如何告诉 mypy 一个数组充满了特定类型的元素,注释 np.ndarray[np.dcomplex]
给出了 mypy 错误 "ndarray" expects no type arguments, but 1 given
.
编辑:这个问题与 as that question was asked 4 years ago when there wasn't any official support for type hinting. I'm asking for what is the official way to do this, now that type hinting is actually natively supported by numpy 1.20. The documentation at 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.NDArray
numpy.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]]
注意,即使你将a
注释为npt.NDArray[np.complex64]
,你仍然需要确保将匹配的dtype
传递给右侧的工厂。
a: npt.NDArray[np.complex64] = np.zeros((3, 3), dtype=np.float32)
同样通过了 mypy 检查。
在 NumPy 1.20 中添加了对类型注释的支持。
我试图弄清楚如何告诉 mypy 一个数组充满了特定类型的元素,注释 np.ndarray[np.dcomplex]
给出了 mypy 错误 "ndarray" expects no type arguments, but 1 given
.
编辑:这个问题与
你要找的是 numpy.typing.NDArray
class: https://numpy.org/doc/stable/reference/typing.html#numpy.typing.NDArray
numpy.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]]
注意,即使你将a
注释为npt.NDArray[np.complex64]
,你仍然需要确保将匹配的dtype
传递给右侧的工厂。
a: npt.NDArray[np.complex64] = np.zeros((3, 3), dtype=np.float32)
同样通过了 mypy 检查。