rustpyo3

Accept HashMap<String, SomePyClass> as function argument in pyo3


I'm trying to get a pyfunction to work in pyo3 that accepts a HashMap<String, SomePyClass> but I get "the trait pyo3::FromPyObject<'_> is not implemented for HashMap<String, Bar>". From what I understand, structs attributed with #[pyclass] do implement FromPyObject [edit: this seems to be incorrect], as does String, as does HashMap<K, V> as long as K and V implement FromPyObject. So what am I doing wrong and how can I get it to work? This is using pyo3 0.21.0-beta.0.


#[pyclass]
struct Bar;

#[pyfunction]
fn example(foo: HashMap<String, Bar>) {}

Solution

  • You need to take PyRef<Class> or PyRefMut<Class>:

    #[pyfunction]
    fn example(foo: HashMap<String, PyRef<'_, Bar>>) {}