Skip to content

Commit b63e256

Browse files
authored
Merge pull request numpy#19396 from defoishugo/fix_numpy.nditer_leak
BUG: fix a numpy.npiter leak in npyiter_multi_index_set
2 parents bdb5cc7 + 8c8da75 commit b63e256

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

numpy/core/src/multiarray/nditer_pywrap.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1601,8 +1601,8 @@ npyiter_multi_index_set(
16011601
for (idim = 0; idim < ndim; ++idim) {
16021602
PyObject *v = PySequence_GetItem(value, idim);
16031603
multi_index[idim] = PyLong_AsLong(v);
1604+
Py_DECREF(v);
16041605
if (error_converting(multi_index[idim])) {
1605-
Py_XDECREF(v);
16061606
return -1;
16071607
}
16081608
}

numpy/core/tests/test_nditer.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,29 @@ def test_iter_c_or_f_order():
185185
assert_equal([x for x in i],
186186
aview.swapaxes(0, 1).ravel(order='A'))
187187

188+
def test_nditer_multi_index_set():
189+
# Test the multi_index set
190+
a = np.arange(6).reshape(2, 3)
191+
it = np.nditer(a, flags=['multi_index'])
192+
193+
# Removes the iteration on two first elements of a[0]
194+
it.multi_index = (0, 2,)
195+
196+
assert_equal([i for i in it], [2, 3, 4, 5])
197+
198+
@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
199+
def test_nditer_multi_index_set_refcount():
200+
# Test if the reference count on index variable is decreased
201+
202+
index = 0
203+
i = np.nditer(np.array([111, 222, 333, 444]), flags=['multi_index'])
204+
205+
start_count = sys.getrefcount(index)
206+
i.multi_index = (index,)
207+
end_count = sys.getrefcount(index)
208+
209+
assert_equal(start_count, end_count)
210+
188211
def test_iter_best_order_multi_index_1d():
189212
# The multi-indices should be correct with any reordering
190213

0 commit comments

Comments
 (0)