我试图键入这样的提示: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
如何正确地键入提示ndarray
?
发布于 2022-06-16 15:45:55
事实证明,强类型的numpy数组一点也不简单。我花了几个小时想办法把它做好。
不向项目添加另一个依赖项的简单方法是使用描述过的这里技巧。只需用'
包装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
的注记
正如@ddejohn所建议的那样,我们可以使用nptyping。只需安装软件包:pip install nptyping
。但是,到目前为止(2022年6月16日),还没有在nptyping
中定义的元组类型,所以您无法以这种方式对代码进行精确的键入。我有发行新的债券,所以也许在将来它会起作用。
编辑
事实证明,有一种不同的方法可以将tuple
表示为nptyping.Shape
,这是萝卜属的回答,这也是很优雅的:
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并不很好地支持此解决方案,这是一个关于形状的错误建议:
Expected class type but received "Literal"
"Literal" is not a class
"Literal" is not a classPylancereportGeneralTypeIssues
Pylance(reportGeneralTypeIssues)
https://stackoverflow.com/questions/68916893
复制相似问题