diff --git a/python/pyarrow/src/arrow/python/python_to_arrow.cc b/python/pyarrow/src/arrow/python/python_to_arrow.cc index a0bae2f50194d..902814a4e91f1 100644 --- a/python/pyarrow/src/arrow/python/python_to_arrow.cc +++ b/python/pyarrow/src/arrow/python/python_to_arrow.cc @@ -1069,7 +1069,8 @@ class PyStructConverter : public StructConverter case KeyKind::BYTES: return AppendDict(dict, bytes_field_names_.obj()); default: - RETURN_NOT_OK(InferKeyKind(PyDict_Items(dict))); + OwnedRef item_ref(PyDict_Items(dict)); + RETURN_NOT_OK(InferKeyKind(item_ref.obj())); if (key_kind_ == KeyKind::UNKNOWN) { // was unable to infer the type which means that all keys are absent return AppendEmpty(); @@ -1115,6 +1116,7 @@ class PyStructConverter : public StructConverter Result> GetKeyValuePair(PyObject* seq, int index) { PyObject* pair = PySequence_GetItem(seq, index); RETURN_IF_PYERROR(); + OwnedRef pair_ref(pair); // ensure reference count is decreased at scope end if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2) { return internal::InvalidType(pair, "was expecting tuple of (key, value) pair"); }