What's the type hint for an array?

Viewed 1788

For most collections we can do:

from typing import List, Tuple, etc

Is there a hint for array? As in:

arr = array.array('i')
1 Answers

As Carcigenicate pointed out, you can use array.array directly as a type annotation. However, you can't use array.array[int] or array.array[float] to specify the type of the elements.

If you need to do this, my suggestion is to use the MutableSequence generic type from the typing module, since arrays implement all of the necessary operations: append, extend, pop, remove, etc.

from typing import MutableSequence

arr: MutableSequence[float] = array.array('f')

In Python 3.9+, you can import it from collections.abc instead.

Related