Skip to main content

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 ::core::option::Option::*;
121        if let ::core::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            ::core::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///
139/// # Examples
140/// ```
141/// use pyo3::prelude::*;
142/// #[pyfunction]
143/// fn add(x: i32, y: i32) -> i32 {
144///     x + y
145/// }
146///
147/// # fn main() -> PyResult<()> {
148/// Python::attach(|py| {
149///     let example = PyModule::from_code(
150///         py,
151///         c"from collections.abc import Callable
152/// def add_two_and_three(add: 'Callable[[int, int], int]') -> int:
153///     return add(2, 3)",
154///         c"example.py",
155///         c"",
156///     )?;
157///
158///     // `add_two_and_three` is a Python function defined in the code above
159///     let add_two_and_three = example.getattr("add_two_and_three")?;
160///
161///     // `add` is a Python function defined by the `#[pyfunction]` macro
162///     let add = wrap_pyfunction!(add, py)?;
163///
164///     let result = add_two_and_three.call1((add,))?.extract::<i32>()?;
165///
166///     assert_eq!(result, 5);
167///
168///     # Ok(())
169/// })
170/// # }
171/// ```
172#[macro_export]
173macro_rules! wrap_pyfunction {
174    ($function:path) => {
175        &|py_or_module| {
176            use $function as wrapped_pyfunction;
177            $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
178                py_or_module,
179                &wrapped_pyfunction::_PYO3_DEF,
180            )
181        }
182    };
183    ($function:path, $py_or_module:expr) => {{
184        use $function as wrapped_pyfunction;
185        $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
186            $py_or_module,
187            &wrapped_pyfunction::_PYO3_DEF,
188        )
189    }};
190}
191
192/// Returns a function that takes a [`Python`](crate::Python) instance and returns a
193/// Python module.
194///
195/// Use this together with [`#[pymodule]`](crate::pymodule) and
196/// [`PyModule::add_wrapped`](crate::types::PyModuleMethods::add_wrapped).
197#[macro_export]
198macro_rules! wrap_pymodule {
199    ($module:path) => {
200        &|py| {
201            use $module as wrapped_pymodule;
202            wrapped_pymodule::_PYO3_DEF
203                .make_module(py)
204                .expect("failed to wrap pymodule")
205        }
206    };
207}
208
209/// Add the module to the initialization table in order to make embedded Python code to use it.
210/// Module name is the argument.
211///
212/// Use it before [`Python::initialize`](crate::marker::Python::initialize) and
213/// leave feature `auto-initialize` off
214#[cfg(not(any(PyPy, GraalPy, all(Py_LIMITED_API, Py_GIL_DISABLED))))]
215#[macro_export]
216macro_rules! append_to_inittab {
217    ($module:ident) => {
218        unsafe {
219            if $crate::ffi::Py_IsInitialized() != 0 {
220                ::core::panic!(
221                    "called `append_to_inittab` but a Python interpreter is already running."
222                );
223            }
224            $crate::ffi::PyImport_AppendInittab(
225                $module::__PYO3_NAME.as_ptr(),
226                ::core::option::Option::Some($module::__pyo3_init),
227            );
228        }
229    };
230}