pub fn clone_py_object(obj: &Py<PyAny>) -> Py<PyAny>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<Py<PyAny>> in callback-holding structs. The original design wrapped
Python callbacks in Arc for thread-safe sharing, but this created circular references:
- Rust
Archolds 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 Py<PyAny> with GIL-based cloning instead of Arc<Py<PyAny>>, 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.