ITADN

Deserialize dataclass as Rust struct/mapping

#93ClosedKobzol 创建于 2025-08-28
K
Kobzolcommented
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: ```rust #[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: ```python @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!
关闭于 2026-02-18 5 条评论