Skip to content

TYP: Fix ndarray.item() and improve ndarray.tolist() #27750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 13, 2024

Conversation

jorenham
Copy link
Member

This fixes the incorrectly annotated ndarray.item method through nested protocols, or for those that like flashy terms, deep structural type matching. Pyright wasn't able to correctly infer the return type of item() before this, but mypy did accept it (even though it shouldn't).
The same trick could be used to effectively re-cycle the (now correct) return type annotation of ndarray.item() to annotate ndarray.tolist() in a DRY way (a rare occurrence in the python-typing world).

The result is that e.g. np.zeros((480, 720, 3), np.uint8).tolist() will now be inferred by static type-checkers as list[list[list[int]]] instead of Any. The tests confirm this is the case with mypy, and I saw that pyright/pylance now also understands it.


I'll soon open another PR that uses the same trick to fix ndarray.real and ndarray.imag.

I'm starting wonder if we could also use this trick to simplify the overloads for specific "array/dtype/scalar-likes" 🤔.

@charris
Copy link
Member

charris commented Nov 13, 2024

The Qemu failures are unrelated.

@charris charris merged commit 7bfdc8c into numpy:main Nov 13, 2024
65 of 70 checks passed
@charris
Copy link
Member

charris commented Nov 13, 2024

Thanks Joren

@jorenham jorenham deleted the typing/ndarray.item branch November 13, 2024 17:16
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