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`](crate::Python::run) 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`](crate::marker::Python::run) instead.
9///
10/// # Examples
11/// ```
12/// use pyo3::{prelude::*, py_run, types::PyList};
13///
14/// Python::with_gil(|py| {
15/// let list = PyList::new(py, &[1, 2, 3]);
16/// py_run!(py, list, "assert list == [1, 2, 3]");
17/// });
18/// ```
19///
20/// You can use this macro to test pyfunctions or pyclasses quickly.
21///
22/// ```
23/// use pyo3::{prelude::*, py_run};
24///
25/// #[pyclass]
26/// #[derive(Debug)]
27/// struct Time {
28/// hour: u32,
29/// minute: u32,
30/// second: u32,
31/// }
32///
33/// #[pymethods]
34/// impl Time {
35/// fn repl_japanese(&self) -> String {
36/// format!("{}時{}分{}秒", self.hour, self.minute, self.second)
37/// }
38/// #[getter]
39/// fn hour(&self) -> u32 {
40/// self.hour
41/// }
42/// fn as_tuple(&self) -> (u32, u32, u32) {
43/// (self.hour, self.minute, self.second)
44/// }
45/// }
46///
47/// Python::with_gil(|py| {
48/// let time = PyCell::new(py, Time {hour: 8, minute: 43, second: 16}).unwrap();
49/// let time_as_tuple = (8, 43, 16);
50/// py_run!(py, time time_as_tuple, r#"
51/// assert time.hour == 8
52/// assert time.repl_japanese() == "8時43分16秒"
53/// assert time.as_tuple() == time_as_tuple
54/// "#);
55/// });
56/// ```
57///
58/// If you need to prepare the `locals` dict by yourself, you can pass it as `*locals`.
59///
60/// ```
61/// use pyo3::prelude::*;
62/// use pyo3::types::IntoPyDict;
63///
64/// #[pyclass]
65/// struct MyClass;
66///
67/// #[pymethods]
68/// impl MyClass {
69/// #[new]
70/// fn new() -> Self {
71/// MyClass {}
72/// }
73/// }
74///
75/// Python::with_gil(|py| {
76/// let locals = [("C", py.get_type::<MyClass>())].into_py_dict(py);
77/// pyo3::py_run!(py, *locals, "c = C()");
78/// });
79/// ```
80#[macro_export]
81macro_rules! py_run {
82 ($py:expr, $($val:ident)+, $code:literal) => {{
83 $crate::py_run_impl!($py, $($val)+, $crate::indoc::indoc!($code))
84 }};
85 ($py:expr, $($val:ident)+, $code:expr) => {{
86 $crate::py_run_impl!($py, $($val)+, &$crate::unindent::unindent($code))
87 }};
88 ($py:expr, *$dict:expr, $code:literal) => {{
89 $crate::py_run_impl!($py, *$dict, $crate::indoc::indoc!($code))
90 }};
91 ($py:expr, *$dict:expr, $code:expr) => {{
92 $crate::py_run_impl!($py, *$dict, &$crate::unindent::unindent($code))
93 }};
94}
95
96#[macro_export]
97#[doc(hidden)]
98macro_rules! py_run_impl {
99 ($py:expr, $($val:ident)+, $code:expr) => {{
100 use $crate::types::IntoPyDict;
101 use $crate::ToPyObject;
102 let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict($py);
103 $crate::py_run_impl!($py, *d, $code)
104 }};
105 ($py:expr, *$dict:expr, $code:expr) => {{
106 use ::std::option::Option::*;
107 if let ::std::result::Result::Err(e) = $py.run($code, None, Some($dict)) {
108 e.print($py);
109 // So when this c api function the last line called printed the error to stderr,
110 // the output is only written into a buffer which is never flushed because we
111 // panic before flushing. This is where this hack comes into place
112 $py.run("import sys; sys.stderr.flush()", None, None)
113 .unwrap();
114 ::std::panic!("{}", $code)
115 }
116 }};
117}
118
119/// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction).
120///
121/// This can be used with [`PyModule::add_function`](crate::types::PyModule::add_function) to add free
122/// functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more information.
123#[macro_export]
124macro_rules! wrap_pyfunction {
125 ($function:path) => {
126 &|py_or_module| {
127 use $function as wrapped_pyfunction;
128 $crate::impl_::pyfunction::_wrap_pyfunction(&wrapped_pyfunction::DEF, py_or_module)
129 }
130 };
131 ($function:path, $py_or_module:expr) => {{
132 use $function as wrapped_pyfunction;
133 $crate::impl_::pyfunction::_wrap_pyfunction(&wrapped_pyfunction::DEF, $py_or_module)
134 }};
135}
136
137/// Returns a function that takes a [`Python`](crate::Python) instance and returns a
138/// Python module.
139///
140/// Use this together with [`#[pymodule]`](crate::pymodule) and
141/// [`PyModule::add_wrapped`](crate::types::PyModule::add_wrapped).
142#[macro_export]
143macro_rules! wrap_pymodule {
144 ($module:path) => {
145 &|py| {
146 use $module as wrapped_pymodule;
147 wrapped_pymodule::DEF
148 .make_module(py)
149 .expect("failed to wrap pymodule")
150 }
151 };
152}
153
154/// Add the module to the initialization table in order to make embedded Python code to use it.
155/// Module name is the argument.
156///
157/// Use it before [`prepare_freethreaded_python`](crate::prepare_freethreaded_python) and
158/// leave feature `auto-initialize` off
159#[cfg(not(PyPy))]
160#[macro_export]
161macro_rules! append_to_inittab {
162 ($module:ident) => {
163 unsafe {
164 if $crate::ffi::Py_IsInitialized() != 0 {
165 ::std::panic!(
166 "called `append_to_inittab` but a Python interpreter is already running."
167 );
168 }
169 $crate::ffi::PyImport_AppendInittab(
170 $module::NAME.as_ptr() as *const ::std::os::raw::c_char,
171 ::std::option::Option::Some($module::init),
172 );
173 }
174 };
175}
176