Skip to content

Commit f058aea

Browse files
committed
BUG: Fix refcounting issue and missed scalar special case for never-copy logic
1 parent 9fee0f8 commit f058aea

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

numpy/core/src/multiarray/ctors.c

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1703,7 +1703,17 @@ PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
17031703
((PyVoidScalarObject *)op)->flags,
17041704
NULL, op);
17051705
}
1706-
else if (cache == 0 && newtype != NULL &&
1706+
/*
1707+
* If we got this far, we definitely have to create a copy, since we are
1708+
* converting either from a scalar (cache == NULL) or a (nested) sequence.
1709+
*/
1710+
if (flags & NPY_ARRAY_ENSURENOCOPY ) {
1711+
PyErr_SetString(PyExc_ValueError,
1712+
"Unable to avoid copy while creating an array.");
1713+
return NULL;
1714+
}
1715+
1716+
if (cache == 0 && newtype != NULL &&
17071717
PyDataType_ISSIGNED(newtype) && PyArray_IsScalar(op, Generic)) {
17081718
assert(ndim == 0);
17091719
/*
@@ -1741,12 +1751,6 @@ PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
17411751

17421752
/* Create a new array and copy the data */
17431753
Py_INCREF(dtype); /* hold on in case of a subarray that is replaced */
1744-
if (flags & NPY_ARRAY_ENSURENOCOPY ) {
1745-
PyErr_SetString(PyExc_ValueError,
1746-
"Unable to avoid copy while creating "
1747-
"an array from descriptor.");
1748-
return NULL;
1749-
}
17501754
ret = (PyArrayObject *)PyArray_NewFromDescr(
17511755
&PyArray_Type, dtype, ndim, dims, NULL, NULL,
17521756
flags&NPY_ARRAY_F_CONTIGUOUS, NULL);

numpy/core/tests/test_multiarray.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7840,6 +7840,9 @@ def test_scalars(self):
78407840
copy=self.RaiseOnBool())
78417841
assert_raises(ValueError, _multiarray_tests.npy_ensurenocopy,
78427842
[1])
7843+
# Casting with a dtype (to unsigned integers) can be special:
7844+
with pytest.raises(ValueError):
7845+
np.array(pyscalar, dtype=np.int64, copy=np._CopyMode.NEVER)
78437846

78447847
def test_compatible_cast(self):
78457848

0 commit comments

Comments
 (0)