-
-
Notifications
You must be signed in to change notification settings - Fork 10.7k
np.clip
typing is not as specific as ideal; existing code doesn't type-check
#18305
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Comments
This behaviour is more widespread than that involving reduction functions like import numpy as np
def sum_axis(x: np.ndarray) -> np.ndarray:
return np.sum(x, axis=1) as the expected type is I've been trying to find the reasoning behind this, I'm not sure if it is ever possible for a reduction function along an axis (as long as EDIT: to expand a little bit, the following pattern either needs an explicit import numpy as np
from typing import cast
def fun(x: np.ndarray) -> np.ndarray:
return x
# type annotation needed here as otherwised inferred as `Any`
arr3d = np.random.rand(3, 4, 5) # type: np.ndarray
# the following is inferred as `Union[number, np.ndarray]`.
arr2d = np.sum(arr3d, axis=2)
# the following will not typecheck:
# error: Argument 1 to "fun" has incompatible type "Union[number[Any], ndarray]"; expected "ndarray"
result = fun(arr2d)
# the following will typecheck
result = fun(arr2d) # type: ignore
# the following will also typecheck
arr2d = cast(np.ndarray, arr2d)
result = fun(arr2d) |
So a PR addressing the issue is up at #18885, the respective backport following later. To summarize (the PR contains more details): the likes of Without the ability the describe 0D arrays (see #16544) it does mean that a sacrifice has to be made, i.e. we cannot describe numpy's 0D-to-scalar casting (or even attempt to) as can't type the array shape/dimensionality in the first place. This is honestly the lesser of two evils, as it will be an inconvenience exclusively only 0D arrays, rather than all arrays of any arbitrary dimensionality. |
The typing definition of
np.clip
always seems to return a union of number or ndarray for any array-like input. Unfortunately this breaks typechecking in existing code we had when we pulled in numpy1.20.0
.It'd be much nicer if it could know when the type returned would be a scalar or a vector based on the input type, which I think should be achievable with the right overloads.
Reproducing code example:
Error message:
See above for reported typechecking error on destructuring.
NumPy/Python version information:
The text was updated successfully, but these errors were encountered: