Skip to content

Instantly share code, notes, and snippets.

@jorenham
Last active July 9, 2026 09:17
Show Gist options
  • Select an option

  • Save jorenham/f91ff9ae7453e4fafabaf4c490545404 to your computer and use it in GitHub Desktop.

Select an option

Save jorenham/f91ff9ae7453e4fafabaf4c490545404 to your computer and use it in GitHub Desktop.
NumPy 2.5.1 stub audit

NumPy stub audit

Stubs and runtime both at numpy/numpy@1832390 (main, 2.6.0.dev0+git20260706.1832390), CPython 3.14.6, Linux x86-64. Checkers: basedpyright 1.39.8 (pyright 1.1.410), mypy 2.1.0. Unless noted, both checkers agree.

Ordered by severity × impact. One entry = one PR. Backport = maintenance/2.5.x.


1. sum/prod/cumsum/cumprod on sub-intp integer arrays: stubs keep the dtype, runtime promotes to intp/uintp

DONE: numpy/numpy#31876

Reductions promote integer dtypes with precision below the default integer (uint8, int16, uint16, int32, uint32, …) to intp/uintp. The stubs return ScalarT as-is. uint8 (images) and int16 (audio) arrays make this a frequent silent wrong type.

def f(i2: npt.NDArray[np.int16]) -> None:
    reveal_type(np.sum(i2))     # signedinteger[_16Bit]
    reveal_type(i2.sum())       # signedinteger[_16Bit]
    reveal_type(i2.prod())      # signedinteger[_16Bit]
    reveal_type(i2.cumsum())    # ndarray[tuple[int], dtype[signedinteger[_16Bit]]]
    reveal_type(np.nansum(i2))  # signedinteger[_16Bit]
>>> np.array([1], dtype=np.int16).sum()
np.int64(1)
>>> np.array([1], dtype=np.uint16).sum()
np.uint64(1)
>>> np.array([1], dtype=np.int16).cumsum().dtype
dtype('int64')

Stubs (all ScalarT-preserving overloads of the reduction stack):

Fix: exclude int8 | int16 | int32 / uint8 | uint16 | uint32 from the dtype-preserving overloads and route them to intp / uintp. int32 → intp is also correct on 32-bit platforms (there int32 == intp). Caveat: np.long on 64-bit Windows is 32-bit and also promotes; not expressible per-platform, long → intp is the pragmatic choice.

Backport: yes — stub-only, wrong scalar type on very popular API.


2. std/var of complex arrays: stubs return complex, runtime returns real float

DONE: numpy/numpy#31880

Runtime std/var of complexfloating input return the real floating of the same precision. The ScalarT: inexact-bounded overloads (# keep in sync with mean) preserve the complex dtype; the list[complex] overloads return complex128. (mean is genuinely dtype-preserving; std/var are not.)

def f(z: npt.NDArray[np.complex128]) -> None:
    reveal_type(z.std())      # complex128
    reveal_type(z.var())      # complex128
    reveal_type(np.std(z))    # complex128
    reveal_type(np.nanvar(z)) # complex128
    reveal_type(np.std(z, axis=0))  # ndarray[..., dtype[complex128]]
>>> np.array([1j, 2j]).std()
np.float64(0.5)
>>> np.std([1j, 2j])
np.float64(0.5)
>>> np.array([1j], dtype=np.complex64).std()
np.float32(0.0)

Stubs:

Fix: narrow the dtype-preserving overloads to ScalarT: floating | timedelta64, and add complexfloating overloads mapping complex64 → float32, complex128 → float64, clongdouble → longdouble (three concrete overloads, or one generic complexfloating[NBit1] → floating[NBit1]); list[complex] overload → float64.

Backport: yes — stub-only, low-risk, silently produces complex where float is guaranteed.


3. _TimeUnitSpec never uses its type parameter: all unit-dependent datetime64/timedelta64 overloads collapse

DONE: numpy/numpy#31874

type _TimeUnitSpec[UnitT: _TD64Unit] = _TD64Unit | tuple[_TD64Unit, SupportsIndex]

UnitT is declared but unused, so _TimeUnitSpec[_IntTD64Unit], _TimeUnitSpec[_DateUnit], … are all the same type and the first __new__ overload always wins, regardless of the unit literal. The unit-dependent datetime64[...]/timedelta64[...] parametrization (and everything downstream: .item(), int(), arithmetic) is wrong for most units:

reveal_type(np.timedelta64(5, 'D').item())          # int
reveal_type(np.datetime64('2021-01-01', 's').item())  # int
reveal_type(np.datetime64(dt.date(2021, 1, 1), 'ns').item())  # date
int(np.timedelta64(5, 'D'))                          # accepted by checkers
>>> np.timedelta64(5, 'D').item()
datetime.timedelta(days=5)
>>> np.datetime64('2021-01-01', 's').item()
datetime.datetime(2021, 1, 1, 0, 0)
>>> np.datetime64(dt.date(2021, 1, 1), 'ns').item()
1609459200000000000
>>> int(np.timedelta64(5, 'D'))
TypeError: Only integer units are allowed for conversion to integers

Stub: __init__.pyi#L1019; the per-overload unit groupings (#L6975-L7014, #L7329-L7343) are already correct and start working once the alias is fixed.

Fix: type _TimeUnitSpec[UnitT: _TD64Unit] = UnitT | tuple[UnitT, SupportsIndex].

Backport: yes — one-line fix, repairs the whole datetime64/timedelta64 unit machinery.


4. Generator.choice on a sequence of ints: stub says int, runtime returns np.int64

DONE:: numpy/numpy#31877

The first overload lumps a: int | _NestedSequence[int] together → int. Correct for choice(5), wrong for choice([1, 2, 3]) (np.int64 is not an int subclass).

def f(rng: np.random.Generator) -> None:
    reveal_type(rng.choice([1, 2, 3]))  # int
>>> type(np.random.default_rng(0).choice([1, 2, 3]))
<class 'numpy.int64'>
>>> type(np.random.default_rng(0).choice([True, False]))
<class 'numpy.bool'>

Stub: random/_generator.pyi#L692-L701

Fix: split the overload: a: int → int, a: _NestedSequence[int] → np.int64 (optionally _NestedSequence[bool] → np.bool first).

Backport: yes — very popular call pattern, unsound scalar type.


5. cumsum/cumprod/cumulative_sum/cumulative_prod on bool arrays: stubs return dtype[bool], runtime returns intp

DONE: numpy/numpy#31876

Same promotion rule as #1 but for np.bool: the accumulate functions promote bool to intp. The ndarray.cumsum/ndarray.cumprod methods already model this correctly (they reveal intp); only the free functions are wrong. np.sum(bool_array) is also already correct.

def f(ab: npt.NDArray[np.bool]) -> None:
    reveal_type(np.cumsum(ab))          # ndarray[tuple[int], dtype[bool]]
    reveal_type(np.cumprod(ab))         # ndarray[tuple[int], dtype[bool]]
    reveal_type(np.cumulative_sum(ab))  # ndarray[tuple[int], dtype[bool]]
    reveal_type(np.nancumsum(ab))       # ndarray[tuple[int], dtype[bool]]
    reveal_type(ab.cumsum())            # ndarray[..., dtype[intp]]  <- methods are correct
>>> np.cumsum(np.array([True, False])).dtype
dtype('int64')
>>> np.cumulative_prod(np.array([True]))
array([1])

Stubs (first overload of each; ScalarT: np.generic resp. ScalarT: np.number | np.bool | np.object_ include np.bool):

Fix: exclude np.bool from the dtype-preserving overloads and add a _ArrayLikeBool_co → intp overload, mirroring what ndarray.cumsum already does. Naturally merges with the PR for #1 if preferred.

Backport: yes — trivial and clear-cut.


6. np.bool - builtins.bool typechecks as int_, raises TypeError for all values

SKIP: adding a -> Never overload is unsound and leads to undefined type-checking behavior

bool.__sub__/__rsub__ accept other: int → int_; builtins.bool is a subtype of int, so np.True_ - True and True - np.True_ typecheck. Runtime boolean subtract is unconditionally a TypeError. (np.bool - np.bool, unary -, and b - 1 are all already modeled correctly.)

reveal_type(np.bool_(True) - True)  # signedinteger[_32Bit | _64Bit]
reveal_type(True - np.bool_(True))  # signedinteger[_32Bit | _64Bit]
>>> np.bool_(True) - True
TypeError: numpy boolean subtract, the `-` operator, is not supported, ...

Stub: __init__.pyi#L5599 (__sub__), #L5608 (__rsub__)

Fix: prepend @overload def __sub__(self, other: py_bool | np.bool, /) -> Never: ... (and the __rsub__ counterpart), mirroring the py_bool | bool_ special-casing __add__ already has at #L5577.

Backport: yes — small, prevents a silently-typed runtime crash.


7. np.piecewise with an all-scalar funclist errors under pyright

DONE: numpy/numpy#31878

np.piecewise(x, [x < 0, x >= 0], [-1, 1]) — the documented, most common call pattern — is rejected by (based)pyright: with no callable in funclist it cannot solve the Tss ParamSpec (Arguments for ParamSpec "Tss@piecewise" are missing). mypy accepts. The scalar case is intended (_PiecewiseFunctions includes _ScalarLike_co), so this is a pyright-compat bug in the overload structure, not a semantic gap.

def f(x: np.ndarray[tuple[int], np.dtype[np.float64]]) -> None:
    np.piecewise(x, [x < 0, x >= 0], [-1.0, 1.0])   # pyright: No overloads match
    np.piecewise(x, [x < 0, x >= 0], [np.sin, 1.0])  # ok (callable present)
>>> x = np.array([-1.0, 2.0])
>>> np.piecewise(x, [x < 0, x >= 0], [-1.0, 1.0])
array([-1.,  1.])

Stub: lib/_function_base_impl.pyi#L473-L496, alias at #L151

Fix: add ParamSpec-free overloads with funclist: _SizedIterable[_ScalarLike_co] ahead of the ParamSpec ones.

Backport: yes — false-positive error on the canonical usage.


8. str_/bytes_ indexing: int/slice rejected (works), [()] accepted (raises)

DONE: numpy/numpy#31879

generic.__getitem__ (scalar indexing with ()/.../empty tuple) shadows the inherited str.__getitem__/bytes.__getitem__, so ordinary indexing and slicing of np.str_/np.bytes_ are checker errors while s[()] — a runtime TypeError — reveals Self.

s = np.str_('ab')
s[0]    # error: No overloads for "__getitem__" match
s[1:]   # error
reveal_type(s[()])  # str_
>>> np.str_('ab')[0], np.str_('ab')[1:], np.bytes_(b'ab')[0]
('a', 'b', 97)
>>> np.str_('ab')[()]
TypeError: string indices must be integers, not 'tuple'

Stub: __init__.pyi#L5060-L5079 (generic.__getitem__), inherited into str_ (#L7517) and bytes_ (#L7504)

Fix: re-declare __getitem__ on str_/bytes_ (or on character) with the typeshed str/bytes signatures.

Backport: optional.


9. RandomState.get_state() bare call: stub says dict, runtime returns the legacy tuple

DONE: numpy/numpy#31881

The legacy: Literal[False] = False overload carries a default, so the no-argument call matches it and reveals dict[str, Any]. The runtime default is legacy=True, which returns the ('MT19937', keys, pos, has_gauss, cached_gaussian) tuple. Also reachable as np.random.get_state().

def f(rs: np.random.RandomState) -> None:
    reveal_type(rs.get_state())  # dict[str, Any]
>>> type(np.random.RandomState(0).get_state())
<class 'tuple'>

Stub: random/mtrand.pyi#L99-L102

Fix: remove the = False default from the first overload; the second overload (legacy: Literal[True] = True) then covers the bare call. Its return can also be narrowed to just the tuple.

Backport: yes — one-line, and state pickling is a common use of this API.


10. np.linalg.slogdet on complex matrices: sign and logabsdet types are swapped

DONE: numpy/numpy#31882

Runtime: sign is complex (of modulus 1) for complex input, logabsdet is always real. SlogdetResult binds sign to the floating parameter and logabsdet to the inexact one — exactly backwards.

def f(c: np.ndarray[tuple[int, int], np.dtype[np.complex128]]) -> None:
    reveal_type(np.linalg.slogdet(c).sign)       # float64
    reveal_type(np.linalg.slogdet(c).logabsdet)  # complex128
>>> r = np.linalg.slogdet(np.array([[1j, 0], [0, 2j]]))
>>> type(r.sign), type(r.logabsdet)
(<class 'numpy.complex128'>, <class 'numpy.float64'>)

Stub: linalg/_linalg.pyi#L198-L201 (SlogdetResult), complex overloads #L527-L537. Batched (3-d+) complex input has the same swap on the array-valued fields.

Fix: swap the roles: sign: _InexactOrArrayT_co, logabsdet: _FloatingOrArrayT_co, and flip the type arguments in the complex overloads (SlogdetResult[np.complex128, np.float64] etc.). The real-input overloads are unaffected (both parameters coincide).

Backport: yes — small, unambiguous, wrong on every complex call.


11. np.datetime64(datetime64, unit) rejected by the stub; documented unit-conversion form

DONE: numpy/numpy#31883

No datetime64.__new__ overload accepts (datetime64, unit); the catch-all takes value: bytes | str | dt.date | None. The timedelta64 analog is accepted (via _ConvertibleToTD64).

np.datetime64(np.datetime64('2021-01-01'), 's')  # error: No overloads for "__new__" match
>>> np.datetime64(np.datetime64('2021-01-01'), 's')
np.datetime64('2021-01-01T00:00:00')

Stub: __init__.pyi#L7324-L7343; _ConvertibleToDT64 exists at #L968 but isn't used with a unit argument.

Fix: add def __new__(cls, value: _ConvertibleToDT64, format: _TimeUnitSpec, /) -> datetime64: ... (unit-parametrized once #3 is fixed).

Backport: yes — small false-positive fix.


12. np.linalg.trace on bool / sub-intp integer matrices: stub preserves dtype, runtime promotes

DONE: numpy/numpy#31885

Same promotion rule as #1: linalg.trace delegates to np.trace (a sum over the diagonal), so bool and sub-default-width integers promote to intp/uintp. The ScalarT: _to_complex overloads preserve them. (np.trace/ndarray.trace return Any — broad, unaffected.)

def f(b: np.ndarray[tuple[int, int], np.dtype[np.bool_]],
      u1: np.ndarray[tuple[int, int], np.dtype[np.uint8]]) -> None:
    reveal_type(np.linalg.trace(b))   # numpy.bool
    reveal_type(np.linalg.trace(u1))  # unsignedinteger[_8Bit]
>>> type(np.linalg.trace(np.eye(2, dtype=bool)))
<class 'numpy.int64'>
>>> type(np.linalg.trace(np.eye(2, dtype=np.uint8)))
<class 'numpy.uint64'>

Stub: linalg/_linalg.pyi#L966 (2-d) and the dtype-preserving 3-d+ overloads at #L979-L990.

Fix: as in #1 — route bool | int8 | int16 | int32 → intp and uint8 | uint16 | uint32 → uintp, preserve the rest.

Backport: optional — piggyback on the #1 conventions.


13. divmod() on np.bool scalars and parametrized timedelta64: pyright-only false reject

SKIP: known long-standing pyright bug that was fixed and then reverted for some stupid reason

divmod(np.True_, np.False_), and divmod(m, m) for m: np.timedelta64[int] or np.timedelta64[dt.timedelta], fail under basedpyright (No overloads for "divmod" match): the builtin divmod protocol solving commits to the first bindable __divmod__ overload (e.g. the timedelta64[Never]-constrained one) and gives up. Direct m.__divmod__(m) and mypy are fine; unparametrized timedelta64/timedelta64[None] work.

def f(mi: np.timedelta64[int]) -> None:
    divmod(np.bool_(True), np.bool_(False))  # pyright: No overloads for "divmod" match
    divmod(mi, mi)                           # pyright: same
>>> divmod(np.bool_(True), np.bool_(True)), divmod(np.timedelta64(5, 'D'), np.timedelta64(2, 'D'))
((np.int8(1), np.int8(0)), (np.int64(2), np.timedelta64(1,'D')))

Stub: __init__.pyi#L5721-L5728 (bool.__rdivmod__), #L7148-L7174 (timedelta64.__divmod__/__rdivmod__)

Fix: make a broad overload bindable first, or add a non-overloaded __rdivmod__ fallback.

Backport: no — checker-interaction fix, needs care.


14. np.linspace(..., retstep=True): step typed as scalar ScalarT, runtime step is neither cast nor scalar

Two provable mismatches in the step element of the returned tuple:

  • array endpoints → the step is an ndarray (broadcast (stop-start)/div), not a scalar;
  • dtype= is never applied to the step at runtime (it's computed from the inputs before the cast), so the dtype: _DTypeLike[ScalarT] → tuple[NDArray[ScalarT], ScalarT] overload is wrong even for scalar endpoints.
def f(a1: np.ndarray[tuple[int], np.dtype[np.float64]]) -> None:
    reveal_type(np.linspace(a1, a1 + 1, 5, retstep=True))
    # tuple[ndarray[..., dtype[float64]], float64]
    reveal_type(np.linspace(0, 1, 5, retstep=True, dtype=np.float32))
    # tuple[ndarray[..., dtype[float32]], floating[_32Bit]]
>>> type(np.linspace(np.zeros(2), np.ones(2), 5, retstep=True)[1])
<class 'numpy.ndarray'>
>>> type(np.linspace(0, 1, 5, retstep=True, dtype=np.float32)[1])
<class 'numpy.float64'>
>>> type(np.linspace(0j, 1j, 5, retstep=True)[1])
<class 'numpy.complex128'>

Stub: _core/function_base.pyi#L179-L190 and #L215-L226; the overloads in between return np.float64 | Any for the step and are Any-saved.

Fix: step type is float64 (real inputs) / complex128 (complex inputs), independent of dtype=, unioned with NDArray[...] to cover array endpoints.

Backport: optional — retstep with array endpoints is uncommon; the dtype half is a silent wrong scalar type.


15. np.tril/np.triu on <2-d input: identity overload, but runtime promotes to 2-d

DONE: numpy/numpy#31886

tril/triu broadcast the input to at least 2-d; a 1-d array comes back as a matrix. The first overload is [ArrayT: np.ndarray](m: ArrayT) -> ArrayT, an identity on shape.

def f(a1: np.ndarray[tuple[int], np.dtype[np.float64]]) -> None:
    reveal_type(np.tril(a1))  # ndarray[tuple[int], dtype[float64]]
>>> np.tril(np.array([1., 2., 3.])).shape
(3, 3)

Stub: lib/_twodim_base_impl.pyi#L195 (tril), #L203 (triu)

Fix: bound the identity overload to 2-d+ shapes (or add a preceding _ToArray1D[ScalarT] → _Array2D[ScalarT] overload).

Backport: optional.


16. RandomState.seed accepts float array-likes; runtime raises TypeError

DONE: numpy/numpy#31888

seed: _ArrayLikeFloat_co | None — but non-integral floats always raise (Cannot cast scalar from dtype('float64') to dtype('int64') according to the rule 'safe'). Also reachable as np.random.seed(1.5).

def f(rs: np.random.RandomState) -> None:
    rs.seed(1.5)  # accepted by both checkers
>>> np.random.RandomState().seed(1.5)
TypeError: Cannot cast scalar from dtype('float64') to dtype('int64') according to the rule 'safe'

Stub: random/mtrand.pyi#L96

Fix: seed: _ArrayLikeInt_co | None = None.

Backport: optional — accepts-invalid rather than wrong result type.


17. np.ix_ with a boolean array: stub preserves dtype[bool], runtime returns nonzero indices (intp)

ix_ replaces boolean inputs with their nonzero indices (documented). The ScalarT: np.generic overloads pass np.bool through.

def f(mask: npt.NDArray[np.bool]) -> None:
    reveal_type(np.ix_(mask))  # tuple[ndarray[tuple[int], dtype[bool]]]
>>> np.ix_(np.array([True, False, True]))[0].dtype
dtype('int64')

Stubs: lib/_index_tricks_impl.pyi#L254-L299 (the ScalarT: np.generic overloads; the Sequence[bool] case happens to land on the Sequence[int] → int_ overload, which is fine).

Fix: add _ArrayLike[np.bool] → tuple[_Array1D[np.intp], ...] overloads before the generic ones.

Backport: optional — real but niche.


18. np.busday_offset without roll: rejects date strings that runtime accepts

The default-roll overloads type dates as datetime64 | dt.date (scalar) / _ArrayLike[datetime64] | _NestedSequence[dt.date] (array), while the required-roll overloads use _ScalarLike_co | dt.date / ArrayLike | .... So np.busday_offset('2020-01-06', 1) is a checker error, but np.busday_offset('2020-01-04', 1, roll='forward') is fine. is_busday/busday_count accept strings everywhere.

np.busday_offset('2020-01-06', 1)                  # error: No overloads match
np.busday_offset('2020-01-04', 1, roll='forward')  # ok
>>> np.busday_offset('2020-01-06', 1)
np.datetime64('2020-01-07')

Stub: _core/multiarray.pyi#L1512-L1530 vs. #L1552-L1571

Fix: widen the default-roll overloads' dates to match the explicit-roll ones.

Backport: optional — small false-positive fix.


19. np.linalg.cond accepts float16/longdouble; runtime always raises

Every cond path goes through svd/inv, and linalg's _commonType only supports f4/f8/c8/c16-castable types: float16 and longdouble raise TypeError: array type float16 is unsupported in linalg for every p. The _to_complex-bounded overloads accept them.

def f(f2: np.ndarray[tuple[int, int], np.dtype[np.float16]]) -> None:
    reveal_type(np.linalg.cond(f2))  # floating[Any]
>>> np.linalg.cond(np.eye(2, dtype=np.float16))
TypeError: array type float16 is unsupported in linalg

Stub: linalg/_linalg.pyi#L513, #L519

Fix: drop float16/longdouble (and clongdouble) from cond's accepted dtypes. (Unlike norm, where only the SVD-backed ord values raise — value-dependent, not fixable in types.)

Backport: no — accepts-invalid on an uncommon dtype.


20. ma.MaskedArray.count(): stub says int, runtime returns np.int64 when masked

count(axis=None) returns self.size (Python int) when mask is nomask, but size - mask.sum() (np.intp) otherwise. The stub commits to int. Same for the free function np.ma.count.

def f(m: np.ma.MaskedArray[tuple[int], np.dtype[np.float64]]) -> None:
    reveal_type(m.count())  # int
>>> type(np.ma.masked_array([1., 2.], mask=[True, False]).count())
<class 'numpy.int64'>
>>> type(np.ma.masked_array([1., 2.]).count())  # nomask
<class 'int'>

Stub: ma/core.pyi#L1787, #L3504

Fix: -> int | intp (value-dependent). The axis=... overloads returning NDArray[int_] are also scalar for 1-d input, but that's not expressible with the current shape-generic MaskedArray — leave those.

Backport: no.


21. RandomState.random_integers scalar call: stub says int, runtime returns np.long

DONE: numpy/numpy#31929

Delegates to randint(..., dtype='l'), whose scalar path returns an np.long scalar (unlike randint(10), which really returns int). Deprecated API. The array overloads already say NDArray[np.long].

def f(rs: np.random.RandomState) -> None:
    reveal_type(rs.random_integers(10))  # int
>>> type(np.random.RandomState(0).random_integers(10))  # DeprecationWarning
<class 'numpy.int64'>

Stub: random/mtrand.pyi#L455-L461

Fix: scalar overload → np.long.

Backport: no — deprecated API.


22. Generator.permuted(x) propagates ndarray subclasses; runtime returns base ndarray

DONE: numpy/numpy#31929

The out: None overload is [ArrayT: np.ndarray](x: ArrayT, ...) -> ArrayT; runtime returns a base-class copy for subclass input.

def f(rng: np.random.Generator, m: np.matrix) -> None:
    reveal_type(rng.permuted(m))  # matrix[tuple[int, int], dtype[Any]]
>>> type(np.random.default_rng(0).permuted(np.matrix([[1, 2], [3, 4]])))
<class 'numpy.ndarray'>

Stub: random/_generator.pyi#L684

Fix: bind ArrayT only on the out=-carrying overload; the out=None overload should return NDArray[Any] (or map dtype through).

Backport: no — subclass inputs are exotic.


Appendix: borderline / cleanup, not counted as bugs

  • linalg.eigvals stale union: since eigvals now always returns complex for real input (d->D signature; _to_real_if_imag_zero in _linalg.py is dead code), the NDArray[float64]/NDArray[float32] union members at _linalg.pyi#L427/#L431 are unreachable and the "depends on the values" NOTE comments (L331, L421) are stale. Union contains the right type → not a mismatch, just cleanup. eig's EigResult[complex128] is already correct.
  • Doubled @overload decorators on timedelta64.__add__ at __init__.pyi#L7031-L7035 (stacked @overload @overload) — harmless, presumably unintended.
  • np.arange rejects datetime.date/datetime.timedelta (np.arange(dt.date(2020, 1, 1), dt.date(2020, 1, 5)) works at runtime → datetime64[D] array); _ArangeScalar (multiarray.pyi#L221) excludes them. Possibly intentional strictness.
  • np.apply_along_axis(np.sum, 0, a2) errors under pyright (ParamSpec binding picks np.sum's out=-overload). Plain callables work; checker interaction, not clearly a stub defect.
  • int(np.void(...)) / float(timedelta64[dt.timedelta]) typecheck via typeshed's Buffer branch of int()/float() matching generic.__buffer__ — raises at runtime, but not fixable in numpy's stubs. Related nit: datetime64 doesn't self-restrict __int__/__float__ the way timedelta64 does.
  • uint64 + int64 → Any (runtime float64) — deliberately Any in the stubs; too-broad is out of scope here.
  • Value/shape-dependent returns left broad by design, verified matching where expressible: eigh/svd/qr/lstsq result dtypes, matrix_rank, percentile/quantile/median (except method="nearest"-style dtype preservation, value-dependent), np.roots, np.real_if_close, histogram*, unique*, meshgrid, gradient, interp, busday_count, fft module, emath, strings module, StringDType basics, Polynomial basics, ufunc methods (reduce/accumulate/outer are Any-based), masked-array arithmetic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment