Skip to content

Deserialize dataclass as Rust struct/mapping #93

@Kobzol

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 FromPyObject
struct Foo {
    a: i32,
}

#[pyfunction]
fn take_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.dataclass
class Foo:
    a: int

ffi.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!

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