-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
NumPy __array_ufunc__
does not work with typing
#6524
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
Thanks for the issue @milliams . My guess is that the |
I've checked Pandas, Dask and AstroPy and while they all implement |
Thanks, I see the same thing re pandas. It makes me think it may be coming from xarray, since it's not just But I'm not sure where it would be coming from. Our |
I think this would need to get updated on the NumPy side. Ideally NumPy ufuncs would be typed to check for from typing import Protocol, TypeVar
class HasArrayUFunc(Protocol):
def __array_ufunc__(ufunc, method, *inputs, **kwargs):
pass
ArrayOrHasArrayUFunc = TypeVar("ArrayOrHasArrayUFunc", ndarray, HasArrayUFunc)
def exp(x: ArrayOrHasArrayUFunc) -> ArrayOrHasArrayUFunc:
... |
Should we open an issue on numpy for this? |
Yes, it's worth discussing. I don't know if there will be a satisfying resolution, though. |
If it's useful for anyone else, here is a hack:
I tried writing a function that mapped |
What is your issue?
When using NumPy functions which have been patched to work with xarray objects using
__array_ufunc__
, typing tools like MyPy do not correctly calculate the return value.For example, the function
np.exp
has been adapted by xarray to return a DataArray if it is passed a DataArray, so that code like the following will work:This code creates an
xr.DataArray
, uses numpy to calculate theexp
of its values and then, since it is returned as axr.DataArray
it can call xarray methods likerename
on it.However, running MyPy on this code gives the error:
This is because there is typing information from NumPy which claims that
np.exp
returnsndarray[Any, dtype[Any]]
.Now, I'm unsure whether this is a bug in xarray not providing the typing information to the
__array_ufunc__
code, a bug in NumPy for not having the flexibility to type these overrides or in MyPy for now allowing for overrides like this to happen but I wanted to star with the place where the observed error occurs.The text was updated successfully, but these errors were encountered: