pyo3/
macros.rs

1/// A convenient macro to execute a Python code snippet, with some local variables set.
2///
3/// # Panics
4///
5/// This macro internally calls [`Python::run_bound`](crate::Python::run_bound) and panics
6/// if it returns `Err`, after printing the error to stdout.
7///
8/// If you need to handle failures, please use [`Python::run_bound`](crate::marker::Python::run_bound) instead.
9///
10/// # Examples
11/// ```
12/// use pyo3::{prelude::*, py_run, types::PyList};
13///
14/// # fn main() -> PyResult<()> {
15/// Python::with_gil(|py| {
16///     let list = PyList::new(py, &[1, 2, 3])?;
17///     py_run!(py, list, "assert list == [1, 2, 3]");
18/// # Ok(())
19/// })
20/// # }
21/// ```
22///
23/// You can use this macro to test pyfunctions or pyclasses quickly.
24///
25/// ```
26/// use pyo3::{prelude::*, py_run};
27///
28/// #[pyclass]
29/// #[derive(Debug)]
30/// struct Time {
31///     hour: u32,
32///     minute: u32,
33///     second: u32,
34/// }
35///
36/// #[pymethods]
37/// impl Time {
38///     fn repl_japanese(&self) -> String {
39///         format!("{}時{}分{}秒", self.hour, self.minute, self.second)
40///     }
41///     #[getter]
42///     fn hour(&self) -> u32 {
43///         self.hour
44///     }
45///     fn as_tuple(&self) -> (u32, u32, u32) {
46///         (self.hour, self.minute, self.second)
47///     }
48/// }
49///
50/// Python::with_gil(|py| {
51///     let time = Py::new(py, Time {hour: 8, minute: 43, second: 16}).unwrap();
52///     let time_as_tuple = (8, 43, 16);
53///     py_run!(py, time time_as_tuple, r#"
54///         assert time.hour == 8
55///         assert time.repl_japanese() == "8時43分16秒"
56///         assert time.as_tuple() == time_as_tuple
57///     "#);
58/// });
59/// ```
60///
61/// If you need to prepare the `locals` dict by yourself, you can pass it as `*locals`.
62///
63/// ```
64/// use pyo3::prelude::*;
65/// use pyo3::types::IntoPyDict;
66///
67/// #[pyclass]
68/// struct MyClass;
69///
70/// #[pymethods]
71/// impl MyClass {
72///     #[new]
73///     fn new() -> Self {
74///         MyClass {}
75///     }
76/// }
77///
78/// # fn main() -> PyResult<()> {
79/// Python::with_gil(|py| {
80///     let locals = [("C", py.get_type::<MyClass>())].into_py_dict(py)?;
81///     pyo3::py_run!(py, *locals, "c = C()");
82/// #   Ok(())
83/// })
84/// # }
85/// ```
86#[macro_export]
87macro_rules! py_run {
88    ($py:expr, $($val:ident)+, $code:literal) => {{
89        $crate::py_run_impl!($py, $($val)+, $crate::indoc::indoc!($code))
90    }};
91    ($py:expr, $($val:ident)+, $code:expr) => {{
92        $crate::py_run_impl!($py, $($val)+, $crate::unindent::unindent($code))
93    }};
94    ($py:expr, *$dict:expr, $code:literal) => {{
95        $crate::py_run_impl!($py, *$dict, $crate::indoc::indoc!($code))
96    }};
97    ($py:expr, *$dict:expr, $code:expr) => {{
98        $crate::py_run_impl!($py, *$dict, $crate::unindent::unindent($code))
99    }};
100}
101
102#[macro_export]
103#[doc(hidden)]
104macro_rules! py_run_impl {
105    ($py:expr, $($val:ident)+, $code:expr) => {{
106        use $crate::types::IntoPyDict;
107        use $crate::conversion::IntoPyObject;
108        use $crate::BoundObject;
109        let d = [$((stringify!($val), (&$val).into_pyobject($py).unwrap().into_any().into_bound()),)+].into_py_dict($py).unwrap();
110        $crate::py_run_impl!($py, *d, $code)
111    }};
112    ($py:expr, *$dict:expr, $code:expr) => {{
113        use ::std::option::Option::*;
114        #[allow(unused_imports)]
115        if let ::std::result::Result::Err(e) = $py.run(&::std::ffi::CString::new($code).unwrap(), None, Some(&$dict)) {
116            e.print($py);
117            // So when this c api function the last line called printed the error to stderr,
118            // the output is only written into a buffer which is never flushed because we
119            // panic before flushing. This is where this hack comes into place
120            $py.run($crate::ffi::c_str!("import sys; sys.stderr.flush()"), None, None)
121                .unwrap();
122            ::std::panic!("{}", $code)
123        }
124    }};
125}
126
127/// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction).
128///
129/// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to
130/// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more
131/// information.
132#[macro_export]
133macro_rules! wrap_pyfunction {
134    ($function:path) => {
135        &|py_or_module| {
136            use $function as wrapped_pyfunction;
137            $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
138                py_or_module,
139                &wrapped_pyfunction::_PYO3_DEF,
140            )
141        }
142    };
143    ($function:path, $py_or_module:expr) => {{
144        use $function as wrapped_pyfunction;
145        $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
146            $py_or_module,
147            &wrapped_pyfunction::_PYO3_DEF,
148        )
149    }};
150}
151
152/// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction).
153///
154/// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to
155/// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more
156/// information.
157#[deprecated(since = "0.23.0", note = "renamed to `wrap_pyfunction!`")]
158#[macro_export]
159macro_rules! wrap_pyfunction_bound {
160    ($function:path) => {
161        $crate::wrap_pyfunction!($function)
162    };
163    ($function:path, $py_or_module:expr) => {
164        $crate::wrap_pyfunction!($function, $py_or_module)
165    };
166}
167
168/// Returns a function that takes a [`Python`](crate::Python) instance and returns a
169/// Python module.
170///
171/// Use this together with [`#[pymodule]`](crate::pymodule) and
172/// [`PyModule::add_wrapped`](crate::types::PyModuleMethods::add_wrapped).
173#[macro_export]
174macro_rules! wrap_pymodule {
175    ($module:path) => {
176        &|py| {
177            use $module as wrapped_pymodule;
178            wrapped_pymodule::_PYO3_DEF
179                .make_module(py, wrapped_pymodule::__PYO3_GIL_USED)
180                .expect("failed to wrap pymodule")
181        }
182    };
183}
184
185/// Add the module to the initialization table in order to make embedded Python code to use it.
186/// Module name is the argument.
187///
188/// Use it before [`prepare_freethreaded_python`](crate::prepare_freethreaded_python) and
189/// leave feature `auto-initialize` off
190#[cfg(not(any(PyPy, GraalPy)))]
191#[macro_export]
192macro_rules! append_to_inittab {
193    ($module:ident) => {
194        unsafe {
195            if $crate::ffi::Py_IsInitialized() != 0 {
196                ::std::panic!(
197                    "called `append_to_inittab` but a Python interpreter is already running."
198                );
199            }
200            $crate::ffi::PyImport_AppendInittab(
201                $module::__PYO3_NAME.as_ptr(),
202                ::std::option::Option::Some($module::__pyo3_init),
203            );
204        }
205    };
206}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here