1

I have a simple class annotated with #[pyclass]

#[pyclass]
pub struct A {
    ...
}

Now I have a function of the form

fn f(slf: Py<Self>) -> PyObject{
   //... some code here
   let output = A{...};
   output.to_object()   // Error: method `to_object` not found for this
}

Should I annotate my struct with something to make it derive pyo3::ToPyObject?

alagris
  • 1,838
  • 16
  • 31

1 Answers1

4

If you have power over the function signature, you can just change it to fn f(slf: Py<Self>) -> A

I prefer this method, wherever possible, because then the conversion just happens under the hood.

If you need to keep the signature general because you might be returning structs of different types, you need to invoke the correct conversion method.

A struct marked with #[pyclass] will have IntoPy<PyObject> implemented, but the conversion method isn't called to_object but rather into_py, and it wants a gil token. So here's what you do:

fn f(slf: Py<Self>) -> PyObject {
  //... some code here
  let gil = Python::acquire_gil()?;
  let py = gil.python();
  output.into_py(py)
}
cadolphs
  • 9,014
  • 1
  • 24
  • 41