Skip to content

Commit

Permalink
exposes Borrowed::to_owned as public API (#3963)
Browse files Browse the repository at this point in the history
* exposes `Borrowed::to_owned` as public API

* add newsfragment
  • Loading branch information
Icxolu authored Mar 17, 2024
1 parent dcba984 commit da24f0c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
1 change: 1 addition & 0 deletions newsfragments/3963.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
added `Borrowed::to_owned`
27 changes: 25 additions & 2 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,8 +511,31 @@ unsafe impl<T> AsPyPointer for Bound<'_, T> {
pub struct Borrowed<'a, 'py, T>(NonNull<ffi::PyObject>, PhantomData<&'a Py<T>>, 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<T>`] 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::<i32>().unwrap(), 1);
/// Ok(())
/// })
/// # }
pub fn to_owned(self) -> Bound<'py, T> {
(*self).clone()
}
}
Expand Down

0 comments on commit da24f0c

Please sign in to comment.