Skip to content

Commit c091f26

Browse files
BUG: Fix __array__(None) to preserve dtype (numpy#28806)
This PR fixes a bug in the __array__ method where calling __array__(None) would return an array with the default dtype float64, regardless of the original array's dtype.
1 parent 91db7fb commit c091f26

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

numpy/_core/src/multiarray/methods.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,7 @@ array_getarray(PyArrayObject *self, PyObject *args, PyObject *kwds)
928928
PyObject *ret;
929929

930930
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&$O&:__array__", kwlist,
931-
PyArray_DescrConverter, &newtype,
931+
PyArray_DescrConverter2, &newtype,
932932
PyArray_CopyConverter, &copy)) {
933933
Py_XDECREF(newtype);
934934
return NULL;

numpy/_core/tests/test_multiarray.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10459,3 +10459,13 @@ def __init__(self, interface):
1045910459
# Now, using np.asanyarray on this dummy should trigger a ValueError (not segfault)
1046010460
with pytest.raises(ValueError, match="dimensions must be within"):
1046110461
np.asanyarray(dummy)
10462+
10463+
@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.uint32, np.complex128])
10464+
def test_array_dunder_array_preserves_dtype_on_none(dtype):
10465+
"""
10466+
Regression test for: https://github.com/numpy/numpy/issues/27407
10467+
Ensure that __array__(None) returns an array of the same dtype.
10468+
"""
10469+
a = np.array([1], dtype=dtype)
10470+
b = a.__array__(None)
10471+
assert_array_equal(a, b, strict=True)

0 commit comments

Comments
 (0)