TYP: numpy allows a datetime array to be divided by another array
Closed this issue · 6 comments
Describe the issue:
If a numpy array has a datetime type, and is divided by another array, typecheckers are not picking that up as wrong.
Reproduce the code example:
from typing import reveal_type
import numpy as np
s = np.array([np.datetime64(f"2025-10-{d:02d}") for d in (23, 24, 25)], np.datetime64)
t = np.array([1, 2, 3])
reveal_type(s)
reveal_type(t)
reveal_type(s.__truediv__(t))
s / tError message:
The type revealed of the division operation is `Any`Python and NumPy Versions:
python 3.12
numpy 2.3.4
Type-checker version and settings:
pyright 1.1.407
mypy 1.18.2
Additional typing packages.
Note: This came up with pandas-stubs.
We think the solution is to add an overload that returns Never .
This only seems to happen when dividing by an array with dtype[Any], in which case the latest overload is selected:
Lines 3154 to 3184 in a0ce2fb
So this false negaative could be fixed by narrowing the self: NDArray[Any] so that it doesn't accept NDArray[np.datetime64] anymore.
This only seems to happen when dividing by an array with
dtype[Any], in which case the latest overload is selected:
It also happens with anything that supports the __array__() interface, which is also true for pandas. So if the divisor is a pandas series, we can't detect that.
This only seems to happen when dividing by an array with
dtype[Any], in which case the latest overload is selected:It also happens with anything that supports the
__array__()interface, which is also true for pandas. So if the divisor is a pandas series, we can't detect that.
Hmm, that sounds more like the second-to-last __rtruediv__ overload.
I take it that pd.Series.__array__ returns NDArray[Any] then?
I take it that
pd.Series.__array__returnsNDArray[Any]then?
Yes