Skip to content

Commit 7177513

Browse files
committed
Merge pull request numpy#2920 from certik/backport2907
BUG: Convert non-array rhs for boolean assignment with correct dtype
2 parents ec58fab + 3087fd5 commit 7177513

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

numpy/core/src/multiarray/mapping.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,9 +1282,17 @@ array_ass_sub(PyArrayObject *self, PyObject *ind, PyObject *op)
12821282
PyArrayObject *op_arr;
12831283
PyArray_Descr *dtype = NULL;
12841284

1285-
op_arr = (PyArrayObject *)PyArray_FromAny(op, dtype, 0, 0, 0, NULL);
1286-
if (op_arr == NULL) {
1287-
return -1;
1285+
if (!PyArray_Check(op)) {
1286+
dtype = PyArray_DTYPE(self);
1287+
Py_INCREF(dtype);
1288+
op_arr = (PyArrayObject *)PyArray_FromAny(op, dtype, 0, 0, 0, NULL);
1289+
if (op_arr == NULL) {
1290+
return -1;
1291+
}
1292+
}
1293+
else {
1294+
op_arr = op;
1295+
Py_INCREF(op_arr);
12881296
}
12891297

12901298
if (PyArray_NDIM(op_arr) < 2) {

numpy/core/tests/test_regression.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,18 @@ def bfb(): x[:] = np.arange(3,dtype=float)
288288
self.assertRaises(ValueError, bfa)
289289
self.assertRaises(ValueError, bfb)
290290

291+
@dec.knownfailureif(sys.version_info < (2, 6),
292+
"See #2920 why this fails")
293+
def test_nonarray_assignment(self):
294+
# See also Issue gh-2870, test for nonarray assignment
295+
# and equivalent unsafe casted array assignment
296+
a = np.arange(10)
297+
b = np.ones(10, dtype=bool)
298+
def assign(a, b, c):
299+
a[b] = c
300+
assert_raises(ValueError, assign, a, b, np.nan)
301+
a[b] = np.array(np.nan) # but not this.
302+
291303
def test_unpickle_dtype_with_object(self,level=rlevel):
292304
"""Implemented in r2840"""
293305
dt = np.dtype([('x',int),('y',np.object_),('z','O')])

0 commit comments

Comments
 (0)