Numpy's recent version 1.20 includes type annotations. This is great, and tools like mypy, instead of complaining about Numpy lacking type information now complain about your code.
This trivial example calculates the centroid of m points of n dimensions that will always return a point:
from numpy import ndarray
def centroid(points: ndarray) -> ndarray:
return points.mean(axis=0)
Before Numpy 1.20, mypy complained with Skipping analyzing numpy. Now it says
Mypy: Incompatible return value type (got "Union[number[Any], ndarray]", expected "ndarray")
because mean() may return a number or an array, but only an array is expected as the return value of centroid().
The warning can be avoided without adding execution time with
return cast(ndarray, points.mean(axis=0))
or simply
return points.mean(axis=0) # type: ignore
Is there a better method without incurring in additional computations?