From da24f0cf937c833763dd94c341a0d4188def40dd Mon Sep 17 00:00:00 2001 From: Icxolu <10486322+Icxolu@users.noreply.github.com> Date: Sun, 17 Mar 2024 10:17:09 +0100 Subject: [PATCH] exposes `Borrowed::to_owned` as public API (#3963) * exposes `Borrowed::to_owned` as public API * add newsfragment --- newsfragments/3963.added.md | 1 + src/instance.rs | 27 +++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 newsfragments/3963.added.md diff --git a/newsfragments/3963.added.md b/newsfragments/3963.added.md new file mode 100644 index 00000000..86da17ac --- /dev/null +++ b/newsfragments/3963.added.md @@ -0,0 +1 @@ +added `Borrowed::to_owned` \ No newline at end of file diff --git a/src/instance.rs b/src/instance.rs index 83775708..024a9fe5 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -511,8 +511,31 @@ unsafe impl AsPyPointer for Bound<'_, T> { pub struct Borrowed<'a, 'py, T>(NonNull, PhantomData<&'a Py>, Python<'py>); impl<'py, T> Borrowed<'_, 'py, T> { - /// Creates a new owned `Bound` from this borrowed reference by increasing the reference count. - pub(crate) fn to_owned(self) -> Bound<'py, T> { + /// Creates a new owned [`Bound`] from this borrowed reference by + /// increasing the reference count. + /// + /// # Example + /// ``` + /// use pyo3::{prelude::*, types::PyTuple}; + /// + /// # fn main() -> PyResult<()> { + /// Python::with_gil(|py| -> PyResult<()> { + /// let tuple = PyTuple::new_bound(py, [1, 2, 3]); + /// + /// // borrows from `tuple`, so can only be + /// // used while `tuple` stays alive + /// let borrowed = tuple.get_borrowed_item(0)?; + /// + /// // creates a new owned reference, which + /// // can be used indendently of `tuple` + /// let bound = borrowed.to_owned(); + /// drop(tuple); + /// + /// assert_eq!(bound.extract::().unwrap(), 1); + /// Ok(()) + /// }) + /// # } + pub fn to_owned(self) -> Bound<'py, T> { (*self).clone() } }