np.ndarray 可以用自定义数据类型注释吗?

Can np.ndarray be annotated with a custom dtype?

我们可以创建具有类似记录属性的 custom dtypes

dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])

我们可以annotate the data type of an ndarray类型提示:

numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

但是,我无法弄清楚如何暗示数组应该具有自定义 dtype,例如 a: NDArray[dt] 导致 Pylance 抱怨:

Declared return type, "ndarray[Any, dtype[Unknown]]", is partially unknown Pylance(reportUnknownVariableType)
Illegal type annotation: variable not allowed unless it is a type alias Pylance(reportGeneralTypeIssues)

我想我想问的是是否可以从 dtype 对象创建类型,或者 +ScalarType 在 numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]].

中的含义

具有如下复合数据类型的数组:

In [98]: dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])
In [99]: arr = np.ones(3, dt)
In [100]: arr
Out[100]: 
array([(1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1)],
      dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')])

此数组的元素,np.void

In [101]: type(arr[0])
Out[101]: numpy.void
In [102]: arr.dtype
Out[102]: dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')])