Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions python/pyarrow/src/arrow/python/python_to_arrow.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1259,6 +1259,7 @@ Status ConvertToSequenceAndInferSize(PyObject* obj, PyObject** seq, int64_t* siz
OwnedRef iter_ref(iter);
PyObject* lst = PyList_New(n);
RETURN_IF_PYERROR();
OwnedRef lst_ref(lst);
for (i = 0; i < n; i++) {
PyObject* item = PyIter_Next(iter);
if (!item) {
Expand All @@ -1270,10 +1271,9 @@ Status ConvertToSequenceAndInferSize(PyObject* obj, PyObject** seq, int64_t* siz
}
// Shrink list if len(iterator) < size
if (i < n && PyList_SetSlice(lst, i, n, NULL)) {
Py_DECREF(lst);
RETURN_IF_PYERROR();
}
*seq = lst;
*seq = lst_ref.detach();
*size = std::min<int64_t>(i, *size);
}
return Status::OK();
Expand Down
23 changes: 23 additions & 0 deletions python/pyarrow/tests/test_convert_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,29 @@ def test_failing_iterator():
pa.array((1 // 0 for x in range(10)), size=10)


def test_failing_iterator_does_not_leak():
# GH-50591
import gc
import sys

# Create an arbitrary long int that is hopefully not cached by the interpreter
value = 10**20

def raising_iter():
for _ in range(5):
yield value
raise ValueError("boom")

gc.collect()
original_refcount = sys.getrefcount(value)

with pytest.raises(ValueError, match="boom"):
pa.array(raising_iter(), size=100)

gc.collect()
assert sys.getrefcount(value) == original_refcount


class ObjectWithOnlyGetitem:
def __getitem__(self, key):
return 3
Expand Down
Loading