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 390011fdd5b..b63326f33a9 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -198,6 +198,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. /// @@ -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)); }) } }