Skip to content

Commit

Permalink
Add Python-ref cloning GILOnceCell::<Py<T>>::clone_ref (#4511)
Browse files Browse the repository at this point in the history
  • Loading branch information
jakelishman authored and davidhewitt committed Sep 15, 2024
1 parent 4824641 commit 5d21295
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions newsfragments/4511.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add Python-ref cloning `clone_ref` for `GILOnceCell<Py<T>>`
16 changes: 15 additions & 1 deletion src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,15 @@ impl<T> GILOnceCell<T> {
}
}

impl<T> GILOnceCell<Py<T>> {
/// Create a new cell that contains a new Python reference to the same contained object.
///
/// Returns an uninitialised cell if `self` has not yet been initialised.
pub fn clone_ref(&self, py: Python<'_>) -> Self {
Self(UnsafeCell::new(self.get(py).map(|ob| ob.clone_ref(py))))
}
}

impl GILOnceCell<Py<PyType>> {
/// Get a reference to the contained Python type, initializing it if needed.
///
Expand Down Expand Up @@ -326,7 +335,12 @@ mod tests {
assert_eq!(cell.get_or_try_init(py, || Err(5)), Ok(&2));

assert_eq!(cell.take(), Some(2));
assert_eq!(cell.into_inner(), None)
assert_eq!(cell.into_inner(), None);

let cell_py = GILOnceCell::new();
assert!(cell_py.clone_ref(py).get(py).is_none());
cell_py.get_or_init(py, || py.None());
assert!(cell_py.clone_ref(py).get(py).unwrap().is_none(py));
})
}
}

0 comments on commit 5d21295

Please sign in to comment.