diff options
-rw-r--r-- | numpy/core/src/multiarray/ctors.c | 18 | ||||
-rw-r--r-- | numpy/core/tests/test_multiarray.py | 3 |
2 files changed, 14 insertions, 7 deletions
diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index 819bb22be..b62426854 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -1703,7 +1703,17 @@ PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth, ((PyVoidScalarObject *)op)->flags, NULL, op); } - else if (cache == 0 && newtype != NULL && + /* + * If we got this far, we definitely have to create a copy, since we are + * converting either from a scalar (cache == NULL) or a (nested) sequence. + */ + if (flags & NPY_ARRAY_ENSURENOCOPY ) { + PyErr_SetString(PyExc_ValueError, + "Unable to avoid copy while creating an array."); + return NULL; + } + + if (cache == 0 && newtype != NULL && PyDataType_ISSIGNED(newtype) && PyArray_IsScalar(op, Generic)) { assert(ndim == 0); /* @@ -1741,12 +1751,6 @@ PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth, /* Create a new array and copy the data */ Py_INCREF(dtype); /* hold on in case of a subarray that is replaced */ - if (flags & NPY_ARRAY_ENSURENOCOPY ) { - PyErr_SetString(PyExc_ValueError, - "Unable to avoid copy while creating " - "an array from descriptor."); - return NULL; - } ret = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, dtype, ndim, dims, NULL, NULL, flags&NPY_ARRAY_F_CONTIGUOUS, NULL); diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 18302543a..4413cd0d0 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -7840,6 +7840,9 @@ class TestArrayCreationCopyArgument(object): copy=self.RaiseOnBool()) assert_raises(ValueError, _multiarray_tests.npy_ensurenocopy, [1]) + # Casting with a dtype (to unsigned integers) can be special: + with pytest.raises(ValueError): + np.array(pyscalar, dtype=np.int64, copy=np._CopyMode.NEVER) def test_compatible_cast(self): |