Skip to content

Commit c9d32a8

Browse files
pvwjakob
authored andcommitted
numpy: fix refcount leak to dtype singleton (#1860)
PyArray_DescrFromType returns a new reference, not borrowed one
1 parent 4a3464f commit c9d32a8

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

include/pybind11/numpy.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1044,7 +1044,7 @@ struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmet
10441044

10451045
static pybind11::dtype dtype() {
10461046
if (auto ptr = npy_api::get().PyArray_DescrFromType_(value))
1047-
return reinterpret_borrow<pybind11::dtype>(ptr);
1047+
return reinterpret_steal<pybind11::dtype>(ptr);
10481048
pybind11_fail("Unsupported buffer format!");
10491049
}
10501050
};

tests/test_numpy_array.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,3 +434,14 @@ def test_array_create_and_resize(msg):
434434
def test_index_using_ellipsis():
435435
a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
436436
assert a.shape == (6,)
437+
438+
439+
@pytest.unsupported_on_pypy
440+
def test_dtype_refcount_leak():
441+
from sys import getrefcount
442+
dtype = np.dtype(np.float_)
443+
a = np.array([1], dtype=dtype)
444+
before = getrefcount(dtype)
445+
m.ndim(a)
446+
after = getrefcount(dtype)
447+
assert after == before

0 commit comments

Comments
 (0)