Creating a Rust object that can be accessed as a dict in Python #5158
-
I have an object in Rust that I'd like to use as a dict in Python. I have read the docs regarding this (https://pyo3.rs/main/class/protocols.html#mapping--sequence-types), but I'm not able to get something working. For instance: #[pyclass(get_all)]
pub struct MyClass {
pub foo: u32,
pub bar: u32,
}
#[pymethods]
impl MyClass {
#[new]
#[pyo3(signature = (
*,
foo = 0,
bar = 0,
))]
fn new(foo: u32, bar: u32) -> Self {
Self {
foo,
bar,
}
}
} And I'd like to be able to create a dict out of it in Python as: >>> my_class = MyClass()
>>> d = dict(my_class)
>>> d["foo"]
0 Or (alternatively) I'd like to be able to get a list of attributes of this class: >>> my_class = MyClass()
>>> my_class.slots() # Or some other function.
("foo", "bar") Is there a way to get PyO3 to do this for me, or do I have to manually implement this functionality? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This functionality is not built in to pyo3. To pass an object to |
Beta Was this translation helpful? Give feedback.
This functionality is not built in to pyo3.
To pass an object to
dict()
constructor, you'll have to implement__iter__
like for a Python type.