Closed
Description
During runtime numpy aggressively casts any passed 0D arrays into their corresponding generic instance. Until the introduction of shape typing (see PEP 646) it is unfortunately not possible to make the necessary distinction between 0D and >0D arrays. While thus not strictly correct, all operations that can potentially perform a 0D-array -> scalar cast are currently annotated as exclusively returning an ndarray.
If it is known in advance that an operation will perform a 0D-array -> scalar cast, then one can consider manually remedying the situation with either typing.cast
or a # type: ignore
comment.
Examples
from typing import cast
import numpy as np
ar_i8 = np.array(1, dtype=np.int64)
# This will yield a `float64` during runtime, but is currently annotated as returning an `ndarray`.
# The output type is manually corrected here via `typing.cast`.
f8 = cast(np.float64, ar_i8 + 1.0)
See Also
#16544: The more general issue on array shape-typing.