Using PyAny to pass Rust-created objects from Python back to Rust

Viewed 613

I have a struct + implementation in Rust that I return to Python. This object can also be passed back to Rust for further work. (In my actual code, I'm using a HashMap<String, MyStruct>, but even just using a struct directly seems to cause the same issues, so my example uses struct Person for simplicity.)

It appears that I need to impl FromPyObject for Person, but Rust can't find PyAny's downcast method

#[pyclass]
struct Person {
    name: String,
    age: u8,
    height_cm: f32,
}

impl pyo3::FromPyObject<'_> for Person {
    fn extract(any: &PyAny) -> PyResult<Self> {
        Ok(any.downcast().unwrap())
               ^^^^^^^^ method not found in `&pyo3::types::any::PyAny`
    }
}

#[pyfunction]
fn make_person() -> PyResult<Person> {
    Ok(Person {
        name: "Bilbo Baggins".to_string(),
        age: 51,
        height_cm: 91.44,
    })
}

#[pyfunction]
fn person_info(py:Python, p: PyObject) -> PyResult<()> {
    let p : Person = p.extract(py)?;
    println!("{} is {} years old", p.name, p.age);
    Ok(())
}

Is this the right way to pass a Rust object from Python back into Rust? If so, what's the right way to use PyAny here?

0 Answers
Related