diff --git a/src/instance.rs b/src/instance.rs index c39b6b387cb..4386afe7755 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -228,6 +228,17 @@ pub(crate) struct Py2Borrowed<'a, 'py, T>( Python<'py>, ); +impl<'py, T> Py2Borrowed<'_, 'py, T> { + /// Creates a new owned `Py2` from this borrowed reference by increasing the reference count. + pub(crate) fn to_owned(self) -> Py2<'py, T> { + unsafe { ffi::Py_INCREF(self.as_ptr()) }; + Py2( + self.py(), + ManuallyDrop::new(unsafe { Py::from_non_null(self.0) }), + ) + } +} + impl<'a, 'py> Py2Borrowed<'a, 'py, PyAny> { /// # Safety /// This is similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by diff --git a/src/types/list.rs b/src/types/list.rs index 5b38db897b0..0d00e0eda27 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -4,6 +4,7 @@ use std::iter::FusedIterator; use crate::err::{self, PyResult}; use crate::ffi::{self, Py_ssize_t}; use crate::ffi_ptr_ext::FfiPtrExt; +use crate::instance::Py2Borrowed; use crate::internal_tricks::get_ssize_index; use crate::types::{PySequence, PyTuple}; use crate::{Py2, PyAny, PyObject, Python, ToPyObject}; @@ -391,7 +392,7 @@ impl<'py> PyListMethods<'py> for Py2<'py, PyList> { // 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_any| borrowed_any.clone()) + .map(Py2Borrowed::to_owned) } }