diff --git a/newsfragments/4511.added.md b/newsfragments/4511.added.md new file mode 100644 index 00000000000..6572ddc7238 --- /dev/null +++ b/newsfragments/4511.added.md @@ -0,0 +1 @@ +Add Python-ref cloning `clone_ref` for `GILOnceCell>` diff --git a/src/sync.rs b/src/sync.rs index c781755c067..33d247b7856 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -197,6 +197,15 @@ impl GILOnceCell { } } +impl GILOnceCell> { + /// 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> { /// Get a reference to the contained Python type, initializing it if needed. /// @@ -325,7 +334,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)); }) } }