[][src]Macro pyo3::py_run

macro_rules! py_run {
    ($py:expr, $($val:ident)+, $code:literal) => { ... };
    ($py:expr, $($val:ident)+, $code:expr) => { ... };
}

A convenient macro to execute a Python code snippet, with some local variables set.

Example

use pyo3::{prelude::*, py_run, types::PyList};
let gil = Python::acquire_gil();
let py = gil.python();
let list = PyList::new(py, &[1, 2, 3]);
py_run!(py, list, "assert list == [1, 2, 3]");

You can use this macro to test pyfunctions or pyclasses quickly.

Example

use pyo3::{prelude::*, py_run, PyCell};
#[pyclass]
#[derive(Debug)]
struct Time {
    hour: u32,
    minute: u32,
    second: u32,
}
#[pymethods]
impl Time {
    fn repl_japanese(&self) -> String {
        format!("{}時{}分{}秒", self.hour, self.minute, self.second)
    }
    #[getter]
    fn hour(&self) -> u32 {
        self.hour
    }
    fn as_tuple(&self) -> (u32, u32, u32) {
        (self.hour, self.minute, self.second)
    }
}
let gil = Python::acquire_gil();
let py = gil.python();
let time = PyCell::new(py, Time {hour: 8, minute: 43, second: 16}).unwrap();
let time_as_tuple = (8, 43, 16);
py_run!(py, time time_as_tuple, r#"
assert time.hour == 8
assert time.repl_japanese() == "8時43分16秒"
assert time.as_tuple() == time_as_tuple
"#);

Note Since this macro is intended to use for testing, it causes panic when Python::run returns Err internally. If you need to handle failures, please use Python::run directly.