Skip to content

Enhance Python Object Deserialization via __dict__ Field #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,18 @@ impl<'de> de::Deserializer<'de> for PyAnyDeserializer<'_> {
if self.0.is_instance_of::<PyFloat>() {
return visitor.visit_f64(self.0.extract()?);
}
if self.0.hasattr("__dict__")? {
return visitor.visit_map(MapDeserializer::new(self.0.getattr("__dict__")?.downcast()?));
}
if self.0.hasattr("__slots__")? {
// __slots__ and __dict__ are mutually exclusive, see
// https://docs.python.org/3/reference/datamodel.html#slots
return visitor.visit_map(MapDeserializer::from_slots(&self.0)?);
}
if self.0.is_none() {
return visitor.visit_none();
}

unreachable!("Unsupported type: {}", self.0.get_type());
}

Expand Down Expand Up @@ -498,6 +507,20 @@ impl<'py> MapDeserializer<'py> {
}
Self { keys, values }
}

fn from_slots(obj: &Bound<'py, PyAny>) -> Result<Self> {
let mut keys = vec![];
let mut values = vec![];
for key in obj.getattr("__slots__")?.try_iter()? {
let key = key?;
keys.push(key.clone());
let v = obj.getattr(key.str()?)?;
values.push(v);
}
Ok(Self {
keys, values
})
}
}

impl<'de> MapAccess<'de> for MapDeserializer<'_> {
Expand Down
51 changes: 50 additions & 1 deletion tests/check_revertible.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{any::Any, collections::HashMap};

Check warning on line 1 in tests/check_revertible.rs

View workflow job for this annotation

GitHub Actions / test

unused imports: `any::Any` and `collections::HashMap`

Check warning on line 1 in tests/check_revertible.rs

View workflow job for this annotation

GitHub Actions / test

unused imports: `any::Any` and `collections::HashMap`

use maplit::hashmap;
use pyo3::prelude::*;
use pyo3::{ffi::c_str, prelude::*};
use serde::{Deserialize, Serialize};
use serde_pyobject::{from_pyobject, to_pyobject};

Expand Down Expand Up @@ -133,3 +135,50 @@
b: 30,
});
}


#[test]
fn check_python_object() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct MyClass {
name: String,
age: i32,
}

Python::with_gil(|py| {
// Create an instance of Python object
py.run(
c_str!(
r#"
class MyClass:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
"#
),
None,
None,
)
.unwrap();
// Create an instance of MyClass
let my_python_class = py
.eval(
c_str!(r#"
MyClass("John", 30)
"#
),
None,
None,
)
.unwrap();

let my_rust_class = MyClass {
name: "John".to_string(),
age: 30,
};
let any: Bound<'_, PyAny> = to_pyobject(py, &my_rust_class).unwrap();
let rust_version: MyClass = from_pyobject(my_python_class).unwrap();
let python_version: MyClass = from_pyobject(any).unwrap();
assert_eq!(rust_version, python_version);
})
}
Loading