Skip to content

Conversation

jorenham
Copy link
Member

@jorenham jorenham commented Mar 14, 2025

Partial backport of numpy/numtype#122 and numpy/numtype#152


This changes resize, empty, zeros, ones, and full, to no longer use Literal int's in the shape-type of the returned array. Type-checkers tend to upcast Literal integers to int when used in generics, so it cannot be reliably used for shape-typing.

I don't expect this to have any impact on type-inference, and even mypy users probably won't even notice any different type-checking behaviour.
But in some cases, this could help make the output of type-checkers less unreadable. For example when an typing error is reported for an array that you created with np.zeros((1080, 1920, 3), dtype=np.uint8), you'd previously see

expected "ndarray[tuple[Literal[1080], Literal[1920], Literal[3]], dtype[unsignedinteger[_8Bit]]]" but received ...

and after this change that would be

expected "ndarray[tuple[int, int, int], dtype[unsignedinteger[_8Bit]]]" but received ...

@jorenham jorenham added 09 - Backport-Candidate PRs tagged should be backported 41 - Static typing numtype Isssue/PR related to numpy/numtype labels Mar 14, 2025

This comment has been minimized.

@jorenham
Copy link
Member Author

jorenham commented Mar 14, 2025

I'm not able to reproduce that mypy_primer error 🤔
(which is irrelevant to this PR, btw)

@jorenham jorenham force-pushed the typing/no-literal-shape-typing branch from 9a57866 to 8e23ae4 Compare March 14, 2025 20:14
Copy link

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

hydpy (https://github.com/hydpy-dev/hydpy)
- hydpy/auxs/ppolytools.py:253: error: Value of type variable "_ShapeType" of "__call__" of "_ConstructorEmpty" cannot be "tuple[int, signedinteger[_64Bit]]"  [type-var]
+ hydpy/auxs/ppolytools.py:253: error: Value of type variable "_AnyShapeType" of "__call__" of "_ConstructorEmpty" cannot be "tuple[int, signedinteger[_64Bit]]"  [type-var]

@charris charris merged commit 99bc87c into numpy:main Mar 15, 2025
74 checks passed
@charris
Copy link
Member

charris commented Mar 15, 2025

Thanks Joren.

@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label Mar 15, 2025
@jorenham jorenham deleted the typing/no-literal-shape-typing branch March 15, 2025 17:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
41 - Static typing numtype Isssue/PR related to numpy/numtype
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants