pub fn clone_py_object(obj: &PyObject) -> PyObject
Expand description
Safely clones a Python object by acquiring the GIL and properly managing reference counts.
This function exists to break reference cycles between Rust and Python that can occur
when using Arc<PyObject>
in callback-holding structs. The original design wrapped
Python callbacks in Arc
for thread-safe sharing, but this created circular references:
- Rust
Arc
holds Python objects โ increases Python reference count. - Python objects might reference Rust objects โ creates cycles.
- Neither side can be garbage collected โ memory leak.
By using plain PyObject
with GIL-based cloning instead of Arc<PyObject>
, we:
- Avoid circular references between Rust and Python memory management.
- Ensure proper Python reference counting under the GIL.
- Allow both Rust and Python garbage collectors to work correctly.
ยงSafety
This function properly acquires the Python GIL before performing the clone operation, ensuring thread-safe access to the Python object and correct reference counting.