TYP: preserve shape-type in ndarray.astype()#28169
Conversation
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Thanks for this.
There's also the numpy.astype dual to numpy.ndarray.astype, and it's probably a good idea to keep those to in sync:
Lines 873 to 886 in 441d1da
After that I'd happy to merge this if the CI and mypy_primer agree 👌🏻.
ndarray.astype()
This patch changes the return type in astype() from NDArray to ndarray so that shape information is preserved and adds tests for it. Similar changes are added to np.astype() for consistency.
754252c to
b866d68
Compare
|
Diff from mypy_primer, showing the effect of this PR on type check results on a corpus of open source code: pandas (https://github.com/pandas-dev/pandas)
- pandas/core/arrays/interval.py:811: error: Incompatible types in assignment (expression has type "ndarray[tuple[int, ...], dtype[Any]]", variable has type "ndarray[tuple[int], dtype[Any]]") [assignment]
- pandas/io/sas/sas_xport.py:249: error: Incompatible types in assignment (expression has type "ndarray[tuple[int, ...], dtype[Any]]", variable has type "ndarray[tuple[int], dtype[Any]]") [assignment]
|
| assert_type(np.astype(i4_2d, np.uint16), np.ndarray[tuple[int, int], np.dtype[np.uint16]]) | ||
| assert_type(f8_3d.astype(np.int16), np.ndarray[tuple[int, int, int], np.dtype[np.int16]]) | ||
| assert_type(np.astype(f8_3d, np.int16), np.ndarray[tuple[int, int, int], np.dtype[np.int16]]) | ||
| assert_type(i4_2d.astype(uncertain_dtype), np.ndarray[tuple[int, int], np.dtype[np.generic[Any]]]) |
There was a problem hiding this comment.
it's fine to leave it like this, but np.generic[Any] is equivalent to np.generic, which is a bit shorter 🤷🏻
|
Thanks @ntrrgc, and welcome aboard! |
|
this might cause some issues for mypy users (and only mypy users), so I'm not not sure if we should backport this @charris |
Does mypy_primer catch those? Also, just to be sure what the diff means, a |
Only for the projects that it checks.
Yea I believe so: red=good here |
This patch changes the return type in astype() from NDArray to ndarray so that shape information is preserved and adds tests for it.