pydict

Macro pydict 

Source
macro_rules! pydict {
    ($py:expr, $($key:expr => $value:expr),*) => { ... };
    ($($key:expr => $value:expr),*) => { ... };
}
Expand description

Create pyo3::types::PyDict from a list of key-value pairs.

§Examples

  • When you have GIL marker py, you can pass it and get a Bound pointer PyResult<Bound<PyDict>>:
use pyo3::{Python, Bound, types::{PyDict, PyDictMethods, PyAnyMethods}};
use serde_pyobject::pydict;

Python::attach(|py| {
    let dict: Bound<PyDict> = pydict! {
        py,
        "foo" => 42,
        "bar" => "baz"
    }
    .unwrap();

    assert_eq!(
        dict.get_item("foo")
            .unwrap()
            .unwrap()
            .extract::<i32>()
            .unwrap(),
        42
    );
    assert_eq!(
        dict.get_item("bar")
            .unwrap()
            .unwrap()
            .extract::<String>()
            .unwrap(),
        "baz",
    );
})
  • When you don’t have GIL marker, you get a PyResult<Py<PyDict>>:
use pyo3::{Python, Py, types::{PyDict, PyDictMethods, PyAnyMethods}};
use serde_pyobject::pydict;

let dict: Py<PyDict> = pydict! {
    "foo" => 42,
    "bar" => "baz"
}
.unwrap();

Python::attach(|py| {
    let dict = dict.into_bound(py);
    assert_eq!(
        dict.get_item("foo")
            .unwrap()
            .unwrap()
            .extract::<i32>()
            .unwrap(),
        42
    );
    assert_eq!(
        dict.get_item("bar")
            .unwrap()
            .unwrap()
            .extract::<String>()
            .unwrap(),
        "baz",
    );
})