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/// Python::with_gil(|py| {
15/// let list = PyList::new_bound(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 = Py::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_bound::<MyClass>())].into_py_dict_bound(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_bound($py);
103 $crate::py_run_impl!($py, *d, $code)
104 }};
105 ($py:expr, *$dict:expr, $code:expr) => {{
106 use ::std::option::Option::*;
107 #[allow(unused_imports)]
108 #[cfg(feature = "gil-refs")]
109 use $crate::PyNativeType;
110 if let ::std::result::Result::Err(e) = $py.run_bound($code, None, Some(&$dict.as_borrowed())) {
111 e.print($py);
112 // So when this c api function the last line called printed the error to stderr,
113 // the output is only written into a buffer which is never flushed because we
114 // panic before flushing. This is where this hack comes into place
115 $py.run_bound("import sys; sys.stderr.flush()", None, None)
116 .unwrap();
117 ::std::panic!("{}", $code)
118 }
119 }};
120}
121
122/// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction).
123///
124/// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to
125/// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more
126/// information.
127///
128/// During the migration from the GIL Ref API to the Bound API, the return type of this macro will
129/// be either the `&'py PyModule` GIL Ref or `Bound<'py, PyModule>` according to the second
130/// argument.
131///
132/// For backwards compatibility, if the second argument is `Python<'py>` then the return type will
133/// be `&'py PyModule` GIL Ref. To get `Bound<'py, PyModule>`, use the [`crate::wrap_pyfunction_bound!`]
134/// macro instead.
135#[macro_export]
136macro_rules! wrap_pyfunction {
137 ($function:path) => {
138 &|py_or_module| {
139 use $function as wrapped_pyfunction;
140 $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
141 py_or_module,
142 &wrapped_pyfunction::_PYO3_DEF,
143 )
144 }
145 };
146 ($function:path, $py_or_module:expr) => {{
147 use $function as wrapped_pyfunction;
148 let check_gil_refs = $crate::impl_::deprecations::GilRefs::new();
149 let py_or_module =
150 $crate::impl_::deprecations::inspect_type($py_or_module, &check_gil_refs);
151 check_gil_refs.is_python();
152 $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
153 py_or_module,
154 &wrapped_pyfunction::_PYO3_DEF,
155 )
156 }};
157}
158
159/// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction).
160///
161/// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to
162/// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more
163/// information.
164#[macro_export]
165macro_rules! wrap_pyfunction_bound {
166 ($function:path) => {
167 &|py_or_module| {
168 use $function as wrapped_pyfunction;
169 $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
170 $crate::impl_::pyfunction::OnlyBound(py_or_module),
171 &wrapped_pyfunction::_PYO3_DEF,
172 )
173 }
174 };
175 ($function:path, $py_or_module:expr) => {{
176 use $function as wrapped_pyfunction;
177 $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction(
178 $crate::impl_::pyfunction::OnlyBound($py_or_module),
179 &wrapped_pyfunction::_PYO3_DEF,
180 )
181 }};
182}
183
184/// Returns a function that takes a [`Python`](crate::Python) instance and returns a
185/// Python module.
186///
187/// Use this together with [`#[pymodule]`](crate::pymodule) and
188/// [`PyModule::add_wrapped`](crate::types::PyModuleMethods::add_wrapped).
189#[macro_export]
190macro_rules! wrap_pymodule {
191 ($module:path) => {
192 &|py| {
193 use $module as wrapped_pymodule;
194 wrapped_pymodule::_PYO3_DEF
195 .make_module(py)
196 .expect("failed to wrap pymodule")
197 }
198 };
199}
200
201/// Add the module to the initialization table in order to make embedded Python code to use it.
202/// Module name is the argument.
203///
204/// Use it before [`prepare_freethreaded_python`](crate::prepare_freethreaded_python) and
205/// leave feature `auto-initialize` off
206#[cfg(not(any(PyPy, GraalPy)))]
207#[macro_export]
208macro_rules! append_to_inittab {
209 ($module:ident) => {
210 unsafe {
211 if $crate::ffi::Py_IsInitialized() != 0 {
212 ::std::panic!(
213 "called `append_to_inittab` but a Python interpreter is already running."
214 );
215 }
216 $crate::ffi::PyImport_AppendInittab(
217 $module::__PYO3_NAME.as_ptr(),
218 ::std::option::Option::Some($module::__pyo3_init),
219 );
220 }
221 };
222}