Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion guide/src/function.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ There are also [`Bound<'_, PyAny>::call0`] with no args and [`Bound<'_, PyAny>::

The ways to convert a Rust function into a Python object vary depending on the function:

- Named functions, e.g. `fn foo()`: add `#[pyfunction]` and then use [`wrap_pyfunction!`] to get the corresponding [`PyCFunction`].
- Named functions, e.g. `fn foo()`: add `#[pyfunction]` and then use [`wrap_pyfunction!`] to get the corresponding [`PyCFunction`]; see [`wrap_pyfunction!`] for an example.
- Anonymous functions (or closures), e.g. `foo: fn()` either:
- use a `#[pyclass]` struct which stores the function as a field and implement `__call__` to call the stored function.
- use `PyCFunction::new_closure` to create an object directly from the function.
Expand Down
32 changes: 32 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,38 @@ macro_rules! py_run_impl {
/// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to
/// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more
/// information.
///
/// # Examples
/// ```
/// use pyo3::prelude::*;
/// #[pyfunction]
/// fn add(x: i32, y: i32) -> i32 {
/// x + y
/// }
///
/// # fn main() -> PyResult<()> {
/// Python::attach(|py| {
/// let example = PyModule::from_code(
/// py,
/// c"from collections.abc import Callable
/// def add_two_and_three(add: Callable[[int, int], int]) -> int:
/// return add(2, 3)",
/// c"example.py",
/// c"",
/// )?;
///
/// let add_two_and_three = example.getattr("add_two_and_three")?;
///
/// let result = add_two_and_three
/// .call1((wrap_pyfunction!(add, example)?,))?
/// .extract::<i32>()?;
///
/// assert_eq!(result, 5);
///
/// # Ok(())
/// })
/// # }
/// ```
#[macro_export]
macro_rules! wrap_pyfunction {
($function:path) => {
Expand Down
Loading