From 4b00a10b8bd47024707f6be0e147370150669a6d Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Thu, 1 Aug 2024 14:35:26 -0600 Subject: [PATCH] Use PyList_GetItemRef in list.get_item() --- src/types/list.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/types/list.rs b/src/types/list.rs index 8f8bd2eb1a4..b10ad6825f3 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -1,9 +1,8 @@ use std::iter::FusedIterator; -use crate::err::{self, PyResult}; +use crate::err::{self, PyErr, PyResult}; use crate::ffi::{self, Py_ssize_t}; use crate::ffi_ptr_ext::FfiPtrExt; -use crate::instance::Borrowed; use crate::internal_tricks::get_ssize_index; use crate::types::{PySequence, PyTuple}; use crate::{Bound, PyAny, PyObject, Python, ToPyObject}; @@ -288,12 +287,12 @@ impl<'py> PyListMethods<'py> for Bound<'py, PyList> { /// }); /// ``` fn get_item(&self, index: usize) -> PyResult> { - unsafe { - // PyList_GetItem return borrowed ptr; must make owned for safety (see #890). - ffi::PyList_GetItem(self.as_ptr(), index as Py_ssize_t) - .assume_borrowed_or_err(self.py()) - .map(Borrowed::to_owned) + let py = self.py(); + let result = unsafe { ffi::compat::PyList_GetItemRef(self.as_ptr(), index as Py_ssize_t) }; + if !result.is_null() { + return Ok(unsafe { result.assume_owned(py) }); } + Err(PyErr::fetch(py)) } /// Gets the list item at the specified index. Undefined behavior on bad index. Use with caution.