I'm having trouble understanding why mypy throws an error with the following example.
import numpy as np
from typing import Sequence
def compute(x: Sequence[float]) -> bool:
# some computation that does not modify x
...
compute(np.linspace(0, 1, 10))
Mypy Error:
Argument 1 to "compute" has incompatible type "ndarray[Any, dtype[floating[Any]]]"; expected "Sequence[float]" [arg-type]
In particular, since typing.Sequence
requires iterability, reversability, and indexing, I'd think a numpy array should also be a Sequence
. Is it related to the fact that numpy arrays are mutable, and Sequence
types are intended to be immutable? I notice when I change Sequence
to Iterable
, the problem is fixed. But I need to be able to index x
in compute
.
So, what is the best way to typehint the compute
function so that it can accept objects with iterability and indexing?