Crates.io | dict_derive |
lib.rs | dict_derive |
version | 0.6.0 |
source | src |
created_at | 2019-06-13 00:01:50.699693 |
updated_at | 2024-08-22 00:15:15.905266 |
description | Derive macros for some PyO3 traits to convert python dicts into rust structs |
homepage | |
repository | https://github.com/gperinazzo/dict-derive |
max_upload_size | |
id | 140712 |
size | 35,130 |
Derive macro for PyO3's FromPyObject
and IntoPy<PyObject>
traits. The derived implementation turns a Python's dict into your Rust struct and back.
Add the library to your Cargo.toml
together with PyO3:
[dependencies]
pyo3 = { version = "0.22", features = ["gil-refs"] }
dict_derive = "0.6"
Import the derive implementation and use it on your structs:
extern crate dict_derive;
use dict_derive::{FromPyObject, IntoPyObject};
#[derive(FromPyObject, IntoPyObject)]
struct User {
name: String,
email: String,
age: u32,
}
Then you can use your structs as arguments and return values in your PyO3 functions:
extern crate pyo3;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
// Requires FromPyObject to receive a struct as an argument
#[pyfunction]
fn get_contact_info(user: User) -> PyResult<String> {
Ok(format!("{} - {}", user.name, user.email))
}
// Requires IntoPyObject to return a struct
#[pyfunction]
fn get_default_user() -> PyResult<User> {
Ok(User {
name: "Default".to_owned(),
email: "default@user.com".to_owned(),
age: 27,
})
}
And then call your functions using normal python dicts:
>>> import mylib
>>> mylib.get_contact_info({"name": "Thor", "email": "thor@asgard.com", "age": 23})
'Thor - thor@asgard.com'
>>> mylib.get_default_user()
{'name': 'Default', 'email': 'default@user.com', 'age': 27}