From 583753e34814ab6804244239bb646d8b7342f6e2 Mon Sep 17 00:00:00 2001 From: Josh Wilson Date: Sun, 29 Mar 2020 16:12:21 -0700 Subject: [PATCH] MAINT: ban setting `ndarray.dtype` See discussion in https://github.com/numpy/numpy-stubs/issues/7. Though this is valid NumPy, users should be using `ndarray.view` instead of setting the dtype, and setting the dtype prevents sensibly making `ndarray` generic over dtype because of situations like this: ``` x = np.ones((2,), dtype=np.int64) # type is ndarray[np.int64] x.dtype = np.bool_ # What is the type now? ``` If someone really wants to do this, they will now have add an ignore, which should make it clear that type safety is going out the window. --- .gitignore | 3 ++- numpy-stubs/__init__.pyi | 2 -- tests/fail/ndarray.py | 11 +++++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 tests/fail/ndarray.py diff --git a/.gitignore b/.gitignore index 0f19c2d..f23c4ae 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ __pycache__ numpy_stubs.egg-info/ venv -.idea \ No newline at end of file +.idea +**~ diff --git a/numpy-stubs/__init__.pyi b/numpy-stubs/__init__.pyi index cb61b7a..0847317 100644 --- a/numpy-stubs/__init__.pyi +++ b/numpy-stubs/__init__.pyi @@ -297,8 +297,6 @@ class ndarray(_ArrayOrScalarCommon, Iterable, Sized, Container): ) -> ndarray: ... @property def dtype(self) -> _Dtype: ... - @dtype.setter - def dtype(self, value: _DtypeLike): ... @property def ctypes(self) -> _ctypes: ... @property diff --git a/tests/fail/ndarray.py b/tests/fail/ndarray.py new file mode 100644 index 0000000..5a5130d --- /dev/null +++ b/tests/fail/ndarray.py @@ -0,0 +1,11 @@ +import numpy as np + +# Ban setting dtype since mutating the type of the array in place +# makes having ndarray be generic over dtype impossible. Generally +# users should use `ndarray.view` in this situation anyway. See +# +# https://github.com/numpy/numpy-stubs/issues/7 +# +# for more context. +float_array = np.array([1.0]) +float_array.dtype = np.bool_ # E: Property "dtype" defined in "ndarray" is read-only