Skip to content

Commit

Permalink
MAINT: ban setting ndarray.dtype
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
person142 committed Mar 29, 2020
1 parent 7d44d93 commit 583753e
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
__pycache__
numpy_stubs.egg-info/
venv
.idea
.idea
**~
2 changes: 0 additions & 2 deletions numpy-stubs/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions tests/fail/ndarray.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 583753e

Please sign in to comment.