numpy array type hint multiple fields

Question:

How do you type hint for numpy arrays with fields like [('reference', 'O'), ('check', '?')] (referenece is to a python object and check is a boolean)

currently my type hint

np.ndarray[typing.Any, np.dtype[[('reference', 'O'), ('check', '?')]]]

doesn’t work as there is a list inside, giving the error List expression not allowed for this type argument(Pylance)

The last I found on this issue is this comment type hint for structured array discussion

Asked By: The unknown

||

Answers:

To type hint for a NumPy array with fields like [(‘reference’, ‘O’), (‘check’, ‘?’)], you can use the following syntax:

import numpy as np

np.ndarray[np.dtype([('reference', 'O'), ('check', '?')]), any]

This syntax specifies that the array should be an ndarray with a structured data type containing the specified fields, and the elements of the array can be of any type.

Here’s an example of how you might use this type hint:

import numpy as np

def foo(arr: np.ndarray[np.dtype([('reference', 'O'), ('check', '?')]), any]) -> None:
    # Do something with arr here
    pass

Note that this type hint is only available in recent versions of Python that support advanced type hints, such as Python 3.6 or later. In earlier versions of Python, you can’t use this syntax to type hint for NumPy arrays with structured data types.

Answered By: Ahmet Buğra BUĞA

Unfortunately we couldn’t expect that structured arrays are supported by a mypy-friendly manner in the near future

This was said by the user odashi in the issue (16 Aug 2022)

The challenges faced by the developers are listed here in this comment of the main numpy
typing issue/discussion

Answered By: The unknown
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.