Description
Describe the issue:
There exists an inconsistency in numpy 2.3 when assigning an array typed to have a scalar type such as np.double
to an array variable typed to have its matching alias such as np.float64
as dtype: For all types except np.float64
and np.complex128
, the assignment passes type checking with mypy, but fails for the other two. (The example below is limited to the floating point numbers, but similar things happen for complex floating numbers.)
This also happens when replacing the scalar type, e.g. when replacing np.double
with np.floating[np._typing._nbit_base._64Bit]
, again with only assignment to float64
failing and all others passing.
From reading some of the recent issues, it was my impression that the assignment of np.floating
to any more concrete dtype should be forbidden, but this seems to only be the case for the aforementioned two types. In any case, I would expect consistent behavior across all three examples. Am I missing a crucial detail here? Or is this an artifact of the changes to np.float64
and np.complex128
introduced in recent versions?
Reproduce the code example:
import numpy as np
import numpy.typing as npt
x_1: npt.NDArray[np.double]= np.array([1], dtype=np.double)
reveal_type(x_1)
y_1: npt.NDArray[np.float64] = x_1
x_2: npt.NDArray[np.half] = np.array([1], dtype=np.half)
reveal_type(x_2)
y_2: npt.NDArray[np.float16] = x_2
x_3: npt.NDArray[np.single] = np.array([1], dtype=np.single)
reveal_type(x_3)
y_3: npt.NDArray[np.float32] = x_3
Error message:
shape2.py:6: note: Revealed type is "numpy.ndarray[builtins.tuple[Any, ...], numpy.dtype[numpy.floating[numpy._typing._nbit_base._64Bit]]]"
shape2.py:7: error: Incompatible types in assignment (expression has type "ndarray[tuple[Any, ...], dtype[floating[_64Bit]]]", variable has type "ndarray[tuple[Any, ...], dtype[float64]]") [assignment]
shape2.py:10: note: Revealed type is "numpy.ndarray[builtins.tuple[Any, ...], numpy.dtype[numpy.floating[numpy._typing._nbit_base._16Bit]]]"
shape2.py:14: note: Revealed type is "numpy.ndarray[builtins.tuple[Any, ...], numpy.dtype[numpy.floating[numpy._typing._nbit_base._32Bit]]]"
Found 1 error in 1 file (checked 1 source file)
Python and NumPy Versions:
2.3.0
3.12.11 | packaged by conda-forge | (main, Jun 4 2025, 14:29:09) [MSC v.1943 64 bit (AMD64)]
Type-checker version and settings:
mypy 1.16.0
Command used: mypy --strict shape2.py
Additional typing packages.
mypy_extensions 1.1.0, typing_extensions 4.14.0, typing-inspection 0.4.1, annotated_types 0.7.0
No stub packages.