From c9d32a81f40ad540015814edf13b29980c63e39c Mon Sep 17 00:00:00 2001 From: Pauli Virtanen Date: Sat, 27 Jul 2019 09:35:32 +0000 Subject: [PATCH] numpy: fix refcount leak to dtype singleton (#1860) PyArray_DescrFromType returns a new reference, not borrowed one --- include/pybind11/numpy.h | 2 +- tests/test_numpy_array.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index e67d3715..8b21d3d4 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -1044,7 +1044,7 @@ public: static pybind11::dtype dtype() { if (auto ptr = npy_api::get().PyArray_DescrFromType_(value)) - return reinterpret_borrow(ptr); + return reinterpret_steal(ptr); pybind11_fail("Unsupported buffer format!"); } }; diff --git a/tests/test_numpy_array.py b/tests/test_numpy_array.py index 17c87ef7..d0a6324d 100644 --- a/tests/test_numpy_array.py +++ b/tests/test_numpy_array.py @@ -434,3 +434,14 @@ def test_array_create_and_resize(msg): def test_index_using_ellipsis(): a = m.index_using_ellipsis(np.zeros((5, 6, 7))) assert a.shape == (6,) + + +@pytest.unsupported_on_pypy +def test_dtype_refcount_leak(): + from sys import getrefcount + dtype = np.dtype(np.float_) + a = np.array([1], dtype=dtype) + before = getrefcount(dtype) + m.ndim(a) + after = getrefcount(dtype) + assert after == before