我正在尝试输入提示 numpy
ndarray
,如下所示:
RGB = numpy.dtype[numpy.uint8]
ThreeD = tuple[int, int, int]
def load_images(paths: list[str]) -> tuple[list[numpy.ndarray[ThreeD, RGB]], list[str]]: ...
但是在我运行此命令的第一行时,出现以下错误:
RGB = numpy.dtype[numpy.uint8]
TypeError: 'numpy._DTypeMeta' object is not subscriptable
如何正确输入提示 a
ndarray
?
事实证明,强类型 numpy 数组根本不简单。我花了几个小时来弄清楚如何正确地做到这一点。
一个不向项目添加另一个依赖项的简单方法是使用here描述的技巧。只需用
'
: 包装 numpy 类型
import numpy
import numpy.typing as npt
from typing import cast, Type, Sequence
import typing
RGB: typing.TypeAlias = 'numpy.dtype[numpy.uint8]'
ThreeD: typing.TypeAlias = tuple[int, int, int]
NDArrayRGB: typing.TypeAlias = 'numpy.ndarray[ThreeD, RGB]'
def load_images(paths: list[str]) -> tuple[list[NDArrayRGB], list[str]]: ...
技巧是使用单引号来避免当Python尝试解释表达式中的TypeError: 'numpy._DTypeMeta' object is not subscriptable
时出现臭名昭著的
[]
。这个技巧可以通过 VSCode Pylance 类型检查器很好地处理:请注意,类型的颜色受到尊重,并且执行不会出现错误。
注意事项
nptyping
nptyping。只需安装软件包即可:pip install nptyping
。但是,截至目前(2022 年 6 月 16 日),
nptyping
中没有定义元组类型,因此您将无法以这种方式完美地输入代码。我已经打开了一个新问题,所以也许将来它会起作用。 编辑
tuple
表达为
nptyping.Shape
,如ramonhagenaars 所回答,这也很优雅:
from nptyping import NDArray, Shape, UInt8
# A 1-dimensional array (i.e. 1 RGB color).
RGBArray1D = NDArray[Shape["[r, g, b]"], UInt8]
# A 2-dimensional array (i.e. an array of RGB colors).
RGBArrayND = NDArray[Shape["*, [r, g, b]"], UInt8]
def load_images_trick(paths: list[str]) -> tuple[list[RGBArrayND], list[str]]: ...
但是,VSCode Pylance 不能很好地支持此解决方案,我收到了关于 Shape 的错误建议:
Expected class type but received "Literal"
"Literal" is not a class
"Literal" is not a classPylancereportGeneralTypeIssues
Pylance(reportGeneralTypeIssues)
pip install numpy --upgrade