8000 DEP: Deprecate setting the dtype of an exact numpy.ndarray by eendebakpt · Pull Request #29244 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

DEP: Deprecate setting the dtype of an exact numpy.ndarray #29244

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

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
DEP: Deprecate setting the dtype of an exact numpy.ndarray
  • Loading branch information
eendebakpt committed Jun 24, 2025
commit 32d5bb1d9df9540182d4a03b7d5ebfc59a7a1894
24 changes: 22 additions & 2 deletions numpy/_core/src/multiarray/getset.c
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,8 @@ array_nbytes_get(PyArrayObject *self, void *NPY_UNUSED(ignored))
* (contiguous or fortran) with compatible dimensions The shape and strides
* will be adjusted in that case as well.
*/
static int
array_descr_set(PyArrayObject *self, PyObject *arg, void *NPY_UNUSED(ignored))
int
array_descr_set_internal(PyArrayObject *self, PyObject *arg)
{
PyArray_Descr *newtype = NULL;

Expand Down Expand Up @@ -522,6 +522,26 @@ array_descr_set(PyArrayObject *self, PyObject *arg, void *NPY_UNUSED(ignored))
return -1;
}

int
array_descr_set(PyArrayObject *self, PyObject *arg)
{
// to be replaced with PyUnstable_Object_IsUniquelyReferenced https://github.com/python/cpython/pull/133144
int unique_reference = (Py_REFCNT(self) == 1);

if (PyArray_CheckExact(self) && (!unique_reference)) {
// this will not emit deprecation warnings for all cases, but for most it will
/* DEPRECATED 2025-06-20, NumPy 2.4 */
int ret = PyErr_WarnEx(PyExc_DeprecationWarning,
"Setting the dtype on a NumPy array has been deprecated in NumPy 2.4.\n"
"Instead of changing the dtype on an array x, create a new array with x.view(new_dtype)",
1);
if (ret) {
return -1;
}
}
return array_descr_set_internal(self, arg);
}

static PyObject *
array_struct_get(PyArrayObject *self, void *NPY_UNUSED(ignored))
{
Expand Down
1 change: 1 addition & 0 deletions numpy/_core/src/multiarray/getset.h
8000
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
#define NUMPY_CORE_SRC_MULTIARRAY_GETSET_H_

extern NPY_NO_EXPORT PyGetSetDef array_getsetlist[];
extern NPY_NO_EXPORT int array_descr_set_internal(PyArrayObject *self, PyObject *arg);

#endif /* NUMPY_CORE_SRC_MULTIARRAY_GETSET_H_ */
15 changes: 14 additions & 1 deletion numpy/_core/src/multiarray/methods.c
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "dtypemeta.h"
#include "item_selection.h"
#include "conversion_utils.h"
#include "getset.h"
#include "shape.h"
#include "strfuncs.h"
#include "array_assign.h"
Expand Down Expand Up @@ -2580,6 +2581,15 @@ array_trace(PyArrayObject *self,

#undef _CHKTYPENUM

static PyObject* array__set_dtype(PyObject *self, PyObject *args)
{
int r = array_descr_set_internal((PyArrayObject *)self, args);

if (r) {
return NULL;
}
Py_RETURN_NONE;
}

static PyObject *
array_clip(PyArrayObject *self,
Expand Down Expand Up @@ -3066,6 +3076,9 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = {
{"to_device",
(PyCFunction)array_to_device,
METH_VARARGS | METH_KEYWORDS, NULL},

// For dtype setting deprecation
{"_set_dtype",
(PyCFunction)array__set_dtype,
METH_O, NULL},
{NULL, NULL, 0, NULL} /* sentinel */
};
4 changes: 4 additions & 0 deletions numpy/_core/tests/test_deprecations.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,11 @@ def test_deprecated_strides_set(self):
x = np.eye(2)
self.assert_deprecated(setattr, args=(x, 'strides', x.strides))

def test_deprecated_dtype_set(self):
x = np.eye(2)
self.assert_deprecated(setattr, x, "dtype", int)


class TestDeprecatedDTypeParenthesizedRepeatCount(_DeprecationTestCase):
message = "Passing in a parenthesized single number"

Expand Down
6 changes: 5 additions & 1 deletion numpy/_core/tests/test_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import random
import sys
import types
import warnings
from itertools import permutations
from typing import Any

Expand Down Expand Up @@ -1225,7 +1226,10 @@ def test_zero_stride(self):
arr = np.broadcast_to(arr, 10)
assert arr.strides == (0,)
with pytest.raises(ValueError):
arr.dtype = "i1"
with warnings.catch_warnings(): # gh-28901
warnings.filterwarnings(action="ignore",
category=DeprecationWarning)
arr.dtype = "i1"

class TestDTypeMakeCanonical:
def check_canonical(self, dtype, canonical):
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_numerictypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ class TestReadValuesNestedMultiple(ReadValuesNested):
class TestEmptyField:
def test_assign(self):
a = np.arange(10, dtype=np.float32)
a.dtype = [("int", "<0i4"), ("float", "<2f4")]
a = a.view(dtype=[("int", "<0i4"), ("float", "<2f4")])
assert_(a['int'].shape == (5, 0))
assert_(a['float'].shape == (5, 2))

Expand Down
2 changes: 1 addition & 1 deletion numpy/lib/_stride_tricks_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def as_strided(x, shape=None, strides=None, subok=False, writeable=True):
array = np.asarray(DummyArray(interface, base=x))
# The route via `__interface__` does not preserve structured
# dtypes. Since dtype should remain unchanged, we set it explicitly.
array.dtype = x.dtype
array._set_dtype(x.dtype)

view = _maybe_view_as_subclass(x, array)

Expand Down
2 changes: 1 addition & 1 deletion numpy/typing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
ndarray
~~~~~~~

It's possible to mutate the dtype of an array at runtime. For example,
It's possible (but deprecated) to mutate the dtype of an array at runtime. For example,
the following code is valid:

.. code-block:: python
Expand Down
0