Home > Software engineering >  Can np.ndarray be annotated with a custom dtype?
Can np.ndarray be annotated with a custom dtype?

Time:04-21

We can create custom dtypes with record-like properties:

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

We can annotate the data type of an ndarray for type hinting:

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

However, I can't work out how to hint that an array is supposed to have a custom dtype, for instance a: NDArray[dt] results in Pylance complaining:

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)

I guess what I'm asking is if is possible to create a type from a dtype object, or what the ScalarType means in numpy.ndarray[typing.Any, numpy.dtype[ ScalarType]].

CodePudding user response:

An array with a compound dtype like this:

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')])

The elements of this array of type, 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')])
  • Related