Skip to content

Deserialize dataclass as Rust struct/mapping #93

Description

@Kobzol

Hi, thanks for the great crate! I'm using it to deserialize things that I can't easily wrap with #[derive(FromPyObject)], but that are serde compatible. On the Python side, I'm using dataclasses a lot, and I'd like to convert them to Rust structs. So I have something like this on the Rust side:

#[derive(serde::Deserialize)]// This can't use FromPyObjectstructFoo{a:i32,}#[pyfunction]fntake_foo<'s>(py:Python,arg:&Bound<'s,PyAny>){
pythonize::depythonize::<Foo>(arg).unwrap();}

and I'd like to send something like this from the Python side:

@dataclasses.dataclassclassFoo:
a: intffi.take_foo(Foo(a=1))

However, currently that ends with an error:

pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value: UnexpectedType("'Foo' object cannot be converted to 'Mapping'")

Is there a way to make it work? I can pre-convert the dataclass to a dictionary with dataclasses.as_dict(Foo(a=1)), but that seems wasteful. FromPyObject is able to read the fields of the object, even if it is not a dictionary, so it seems like depythonize could also do that.

Thanks for your answer!

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions