Modifying the attributes of a python object with pyo3

I'm trying to write python extensions in Rust with pyo3 (v1.13.0) after some initial work with cpython.

In cpython, I was able to define a custom class in Python, pass it to a Rust function as a PyObject and modify its attributes using the PyObject's setattr method.
In pyo3, the PyOjbect class doesn't seem to have a setattr method.
PyAny does have a setattr method, but that seems to be more appropriate for classes defined in Rust itself. When I use PyAny, I get an error that I haven't implemeneted traits, but I don't wan't to have to implement any traits for this class - it's defined in Python.

Any thoughts?

thanks,

Chris

PyAny: Represents any Python object. All Python objects can be cast to PyAny .

I think pyo3::prelude::PyAny - Rust is the way to go.
Unless it does not work.

You probably start with PyObject (Py<PyAny>).
With Py::as_ref that can be turned into &PyAny.
Now you can use setattr.

Using Py::as_ref successfully modified attributes of the passed Python defined object test_obj in this simple test when called from Python:

#[pyfunction]
fn modify_attributes(py: Python, test_obj: PyObject) -> PyResult {
let temp_ref = Py::as_ref(&test_obj, py);
temp_ref.setattr("counts", vec![0,2,3,4])?;

Ok(test_obj)

}

Feels weird to have multiple references to an object in Rust when one is mutable, but I guess that's just a necessary evil of mixing Python and Rust in that way.

Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.