Skip to content

TYP: broadcast_to shape-typing - #32247

Merged
charris merged 1 commit into
numpy:mainfrom
jorenham:typing/broadcast_to/shape-typing
Aug 11, 2026
Merged

charris merged 1 commit into
numpy:mainfrom
jorenham:typing/broadcast_to/shape-typing

Conversation

@jorenham

@jorenham jorenham commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

TLDR; broadcast_to used to ignore all shape types, now it propagates it whenever shape is a tuple.


The stubs for np.broadcast_to completely ignored the shape type, even though there are many common usecases where it (viz. the shape-type) can be exactly statically known.

This propages the shape-types in case it's assignable to tuple[int, ..] (so e.g. shape=[1, 2] wouldn't work, because type-checkers aren't able to statically determine the size of a list like they can for tuples -- lists are mutable and homogeneous, whereas tuples are immutable an heterogeneous).

There's one annoying thing here though: some typecheckers such as pyright propagate the Literal intergers "inside" the tuple shape-type, but others (like mypy) don't. So broadcast_to(a, (1, 2)) will have a shape-type of tuple[int, int] according to mypy, whereas pyright will infer it as tuple[Literal[1], Literal[2]]. I could've worked around this (using finite constrained type variables), but that would've harmed generality. These int vs Literal[] difference also won't matter in the real word, because both are assignable to int, and broadcast_to only accepts positive integers (unlike e.g. reshape, which accepts negative integers, which in this case could have lead to nonsensical shape-types in case of e.g. shape=(2, -1)). So nothing to worry about, just something worth noting.


Fully written by me, pre-reviewed and audited by AI (see this rank-typing tracker hist for details).

@jorenham jorenham added this to the 2.6.0 Release milestone Aug 11, 2026
@github-actions

This comment has been minimized.

@jorenham
jorenham force-pushed the typing/broadcast_to/shape-typing branch from f4bb765 to 800502c Compare August 11, 2026 10:09
@github-actions

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:

optuna (https://github.com/optuna/optuna)
  ./optuna/study/_multi_objective.py:182: error: INTERNAL ERROR -- Please try using mypy master on GitHub:

@charris
charris merged commit bdee8a1 into numpy:main Aug 11, 2026
14 checks passed
@charris

charris commented Aug 11, 2026

Copy link
Copy Markdown
Member

Thanks Joren.

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