-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
TYP: Return type for logical_or too narrow #28162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This error is caused by a limitation in mypy's type inference system, and won't occur with other typecheckers like pyright or basedpyright. See #27957 for a (rather lengthy) discussion on this in detail. Luckily, there's an easy workaround: import numpy as np
import numpy.typing as npt
components_proper = np.random.random([3, 3]) - 0.5
components_improper = np.random.random([3, 3]) - 0.5
in_SST_: npt.NDArray[np.bool] | np.bool
if np.random.randint(1, 3) > 1:
in_SST_ = np.logical_or(
np.all(components_proper >= 0.0, axis=-1),
np.all(components_improper >= 0.0, axis=-1),
)
else:
in_SST_ = np.all(components_proper >= 0.0, axis=-1) This helps mypy to understand what the common denominator of But even so, you're right in saying that the return type of numpy/numpy/_typing/_ufunc.pyi Lines 163 to 190 in 1e10174
NDArray[Any] . If a union of scalar and array is passed, we get an incorrect result.
Somehow this has gone by unnoticed for 4 years, so thanks for reporting this! Some related issues: |
FYI, there's a newer |
@jorenham Actually, I think everything is correct for the typehint in line 190, at least for the case I had in mind. If only one of the arguments of |
The bug is rather subtle: import numpy as np
import numpy.typing as npt
a: npt.NDArray[np.float64] | np.float64
b: npt.NDArray[np.float64] | np.float64
out = np.logical_or(a, b)
reveal_type(out) # npt.NDArray[Any] So |
Describe the issue:
It seems that
logical_or
is annotated to return"ndarray[tuple[int, ...], dtype[Any]]"
, but it returns a single bool when called with scalar arguments. Probably otherlogical_xxx
functions show the same behavior.I could try to fix it (Returning a union of bool and the current annotation), but need someone pointing me at the location of the annotation.
Reproduce the code example:
Error message:
Python and NumPy Versions:
NumPy 2.2.1
Python 3.13.1
Type-checker version and settings:
MyPy: 1.14.0
Additional typing packages.
n/a
The text was updated successfully, but these errors were encountered: