Skip to main content

clone_py_object

Function clone_py_object 

Source
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:

  1. Rust Arc holds Python objects → increases Python reference count.
  2. Python objects might reference Rust objects → creates cycles.
  3. 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.