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`](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/// # fn main() -> PyResult<()> {
15/// Python::attach(|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::attach(|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::attach(|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    // unindent the code at compile time
89    ($py:expr, $($val:ident)+, $code:literal) => {{
90        $crate::py_run_impl!($py, $($val)+, $crate::impl_::unindent::unindent!($code))
91    }};
92    ($py:expr, *$dict:expr, $code:literal) => {{
93        $crate::py_run_impl!($py, *$dict, $crate::impl_::unindent::unindent!($code))
94    }};
95    // unindent the code at runtime
96    ($py:expr, $($val:ident)+, $code:expr) => {{
97        $crate::py_run_impl!($py, $($val)+, $crate::impl_::unindent::unindent($code))
98    }};
99    ($py:expr, *$dict:expr, $code:expr) => {{
100        $crate::py_run_impl!($py, *$dict, $crate::impl_::unindent::unindent($code))
101    }};
102}
103
104/// Internal implementation of the `py_run!` macro.
105///
106/// FIXME: this currently unconditionally allocates a `CString`. We should consider making this not so:
107/// - Maybe require users to pass `&CStr` / `CString`?
108/// - Maybe adjust the `unindent` code to produce `&Cstr` / `Cstring`?
109#[macro_export]
110#[doc(hidden)]
111macro_rules! py_run_impl {
112    ($py:expr, $($val:ident)+, $code:expr) => {{
113        use $crate::types::IntoPyDict;
114        use $crate::conversion::IntoPyObject;
115        use $crate::BoundObject;
116        let d = [$((stringify!($val), (&$val).into_pyobject($py).unwrap().into_any().into_bound()),)+].into_py_dict($py).unwrap();
117        $crate::py_run_impl!($py, *d, $code)
118    }};
119    ($py:expr, *$dict:expr, $code:expr) => {{
120        use ::std::option::Option::*;
121        if let ::std::result::Result::Err(e) = $py.run(&::std::ffi::CString::new($code).unwrap(), None, Some(&$dict)) {
122            e.print($py);
123            // So when this c api function the last line called printed the error to stderr,
124            // the output is only written into a buffer which is never flushed because we
125            // panic before flushing. This is where this hack comes into place
126            $py.run(c"import sys; sys.stderr.flush()", None, None)
127                .unwrap();
128            ::std::panic!("{}", $code)
129        }
130    }};
131}
132
133/// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction).
134///
135/// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to
136/// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more
137/// information.
138#[macro_export]
139macro_rules! wrap_pyfunction {
140    ($function:path) => {
141        &|py_or_module| {
142            use $function as wrapped_pyfunction;
143            $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
144                py_or_module,
145                &wrapped_pyfunction::_PYO3_DEF,
146            )
147        }
148    };
149    ($function:path, $py_or_module:expr) => {{
150        use $function as wrapped_pyfunction;
151        $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
152            $py_or_module,
153            &wrapped_pyfunction::_PYO3_DEF,
154        )
155    }};
156}
157
158/// Returns a function that takes a [`Python`](crate::Python) instance and returns a
159/// Python module.
160///
161/// Use this together with [`#[pymodule]`](crate::pymodule) and
162/// [`PyModule::add_wrapped`](crate::types::PyModuleMethods::add_wrapped).
163#[macro_export]
164macro_rules! wrap_pymodule {
165    ($module:path) => {
166        &|py| {
167            use $module as wrapped_pymodule;
168            wrapped_pymodule::_PYO3_DEF
169                .make_module(py)
170                .expect("failed to wrap pymodule")
171        }
172    };
173}
174
175/// Add the module to the initialization table in order to make embedded Python code to use it.
176/// Module name is the argument.
177///
178/// Use it before [`Python::initialize`](crate::marker::Python::initialize) and
179/// leave feature `auto-initialize` off
180#[cfg(not(any(PyPy, GraalPy)))]
181#[macro_export]
182macro_rules! append_to_inittab {
183    ($module:ident) => {
184        unsafe {
185            if $crate::ffi::Py_IsInitialized() != 0 {
186                ::std::panic!(
187                    "called `append_to_inittab` but a Python interpreter is already running."
188                );
189            }
190            $crate::ffi::PyImport_AppendInittab(
191                $module::__PYO3_NAME.as_ptr(),
192                ::std::option::Option::Some($module::__pyo3_init),
193            );
194        }
195    };
196}