pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

`Clone` (or alternative) on `GILOnceCell`

Open jakelishman opened this issue 1 year ago • 1 comments

I have a pyclass struct that wants to contain a GILOnceCell<Py<PyAny>> for caching of a lazily constructed Python object, where the initialiser yields control to the Python interpreter so runs the risk of re-entrancy problems with regular OnceCell.

I'd originally tried to derive Clone on my struct (I'm still using py-clone for the time being, but working to disentangle our data structures), which if I understand correctly must fail for GILOnceCell because it requires the GIL to mediate both gets and sets. For the time being, I think the correct course of action for me for the clone is to manually GILOnceCell::new(other_cell.get(py).map(|ob| ob.clone_ref(py))) (or similar).

edit: if there's an A/B problem here, and there's something better I could be doing with this kind of cache, I'm totally open to alternatives to the answer being "that's not the right way to do this".

Would it be possible to either:

  • add an impl<T> GILOnceCell<Py<T>> { pub fn clone_ref(&self, py: Python); } method doing what I sketched?
  • give GILOnceCell the proposed derive macro for this kind of "clone with the GIL", if that is what comes out of #4133?

jakelishman avatar Aug 09 '24 12:08 jakelishman