Skip to content

TYP: fix int promotion for *sum and *prod - #31876

Merged
charris merged 3 commits into
numpy:mainfrom
jorenham:typing/sum-prod-int-promotion
Jul 6, 2026
Merged

charris merged 3 commits into
numpy:mainfrom
jorenham:typing/sum-prod-int-promotion

Conversation

@jorenham

@jorenham jorenham commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

The *sum and *prod functions and corresponding ndarray methods were incorrectly propagating the integer (and sometimes bool) dtypes of input. But at runtime, these are promoted to int_:

>>> np.array([1], dtype=np.int16).sum()
np.int64(1)
>>> np.array([1], dtype=np.int16).cumsum().dtype
dtype('int64')

This applies to

  • sum / prod
  • cumsum / cumprod
  • cumulative_sum / cumulative_prod
  • ndarray.sum / ndarray.prod
  • ndarray.cumsum / ndarray.cumprod
  • ma.MaskedArray.cumsum / ma.MaskedArray.cumprod

Fully written by me (a human, I think); bug found by Claude Fable 5 (high) (here's the full audit for those interested).

@jorenham jorenham added 09 - Backport-Candidate PRs tagged should be backported 41 - Static typing labels Jul 6, 2026
@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown

Diff from mypy_primer, showing the effect of this PR on type check results on a corpus of open source code:

jax (https://github.com/google/jax)
- jax/_src/numpy/hijax.py:269: error: Incompatible types in assignment (expression has type "tuple[Any, ...]", variable has type "ndarray[tuple[Any, ...], dtype[float64]]")  [assignment]
+ jax/_src/numpy/hijax.py:269: error: Incompatible types in assignment (expression has type "tuple[Any, ...]", variable has type "ndarray[tuple[Any, ...], dtype[signedinteger[Any]]]")  [assignment]

@charris
charris merged commit 28fa45a into numpy:main Jul 6, 2026
14 checks passed
@jorenham
jorenham deleted the typing/sum-prod-int-promotion branch July 6, 2026 17:05
@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label Jul 6, 2026
charris pushed a commit that referenced this pull request Jul 6, 2026
MaanasArora pushed a commit to MaanasArora/numpy that referenced this pull request Jul 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants