#macro-derive #pyo3 #dictionary #python #struct #convert #traits

macro dict_derive

Derive macros for some PyO3 traits to convert python dicts into rust structs

8 releases (4 breaking)

0.5.0 Nov 3, 2023
0.4.0 Aug 3, 2021
0.3.1 Jan 26, 2021
0.3.0 Sep 16, 2020
0.1.1 Jun 16, 2019

#149 in Procedural macros

Download history 689/week @ 2023-11-24 724/week @ 2023-12-01 535/week @ 2023-12-08 688/week @ 2023-12-15 317/week @ 2023-12-22 544/week @ 2023-12-29 549/week @ 2024-01-05 540/week @ 2024-01-12 695/week @ 2024-01-19 679/week @ 2024-01-26 675/week @ 2024-02-02 798/week @ 2024-02-09 628/week @ 2024-02-16 1187/week @ 2024-02-23 1542/week @ 2024-03-01 580/week @ 2024-03-08

4,075 downloads per month
Used in 4 crates

Apache-2.0

10KB
163 lines

Dict-Derive

Derive macro for PyO3's FromPyObject and IntoPy<PyObject> traits. The derived implementation turns a Python's dict into your Rust struct and back.

Usage

Add the library to your Cargo.toml together with PyO3:

[dependencies]
pyo3 = "0.14.1"
dict_derive = "0.4.0"

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}

Older PyO3 versions

  • For PyO3 version 0.7.0 or lower, use version 0.1 of this crate.
  • For PyO3 version 0.8 to 0.10, use version 0.2 of this crate.
  • For PyO3 version 0.11 to 0.13, use version 0.3 of this crate.
  • For PyO3 version 0.14 to 0.19, use version 0.4 of this crate.

Dependencies

~1.5MB
~34K SLoC