I would like to convert a Python dictionary to a Rust struct in the framework of pyo3
. Specifically, I have a Rust struct that looks like
struct MyStruct {
key_1: Option<String>,
key_2: Option<i32>,
key_3: Option<bool>,
}
I would like to take a Python dictionary and assign matching keys, if they exist, ignoring the rest.
e.g.
my_dict = { 'key_1': 'value_1', 'key_3': True, 'invalid_key': 42 }
should result in the MyStruct
MyStruct {
key_1: Some("value_1"),
key_2: None,
key_3: Some(true),
}
I attempted to do this by marking MyStruct
with the pyo3::pyclass
attribute, but receive the Python error TypeError: argument 'my_dict': 'dict' object cannot be converted to 'MyStruct'
. I then tried to implment the pyo3::FromPyObject
trait for MyStruct
, but receive the Rust error conflicting implementation in crate 'pyo3': - impl<'a, T> pyo3::FromPyObject<'a> for Twhere T: PyClass, T: Clone;
, which I guess is being implemented from pyclass
.
Is there a way to implement this Python dictionary to Rust struct conversion?
Caveat
I would also like to map fields from the Python dictionary to fields with different names in the Rsut struct.
e.g.
my_dict = { 'str_val': 'a string', 'bool_val': false, 'num_val': -1}
should be mapped to
MyStruct {
key_1: Some("a string"),
key_2: Some(false),
key_3: Some(-1),
}