TYP: Fix ndarray.item()
and improve ndarray.tolist()
#27750
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 ofitem()
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 annotatendarray.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 aslist[list[list[int]]]
instead ofAny
. 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
andndarray.imag
.I'm starting wonder if we could also use this trick to simplify the overloads for specific "array/dtype/scalar-likes" 🤔.