Skip to content

Instantly share code, notes, and snippets.

@gilescope
Created July 9, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilescope/041bcdd06c2c94e10c93b4bb801b5929 to your computer and use it in GitHub Desktop.
Save gilescope/041bcdd06c2c94e10c93b4bb801b5929 to your computer and use it in GitHub Desktop.
pyo3 types
Py<PyList> (These are python PyNativeTypes)      <--- into() ---- PyList
    |                                                                 |  (deref/as_ref() )
   \/                                                                \/
PyObject   ------------------------------------- as_ref(py) -----> &PyAny (This links it with a 'py gil lock)
    ^ (clone_ref is a cheap clone)                                    ^
    | .into()                                                         | (deref/as_ref() or .downcast() to go the other way)
    |                                                                 |
Py<MyRustStruct> (These are rust PyClass)                         &PyCell<MyRustStruct>  -- try borrow ------> PyRef<MyRustClass> ----- extract() --> &MyRustClass
    | .as_ref(py)                                                                        -- try borrow_mut --> PyRefMut<MyRustClass> -- extract() --> &mut MyRustClass
   \/
&MyRustStruct
@davidhewitt
Copy link

Responding to Gitter questions...

PyList in the top-right should probably be &PyList - it's got the same 'py lifetime as &PyAny.

Also PyRef<MyRustClass> ---- deref() ---> &MyRustClass. (Similar for deref_mut for PyRefMut.)

All the python types are under the control of the Python GC. The reference count is the main mechanic how the Python GC tracks live objects. (It uses tracing only lightly when trying to detect cycles.)

clone_ref increments the reference count and puts ownership of that new count into the PyObject. It's essentially equivalent to .clone() since I added impl Clone to Py and PyObject in PyO3 0.10.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment