liveBook · Manning

Pyfunction attribute macro

As explained in Refactoring to Rust

The pyfunction attribute macro is a PyO3 macro that generates a Python-compatible wrapper for a Rust function.

The #[pyfunction] attribute macro marks a Rust function for exposure to Python by generating the Python-compatible wrapper required by PyO3. The function must also be registered with the module using wrap_pyfunction!. section 6.4

A minimal exposed function has two integration points:

  • Place #[pyfunction] immediately before the Rust function. section 6.4
  • Call m.add_function(wrap_pyfunction!(sum, m)?)? inside the #[pymodule] function. section 6.4

Calling the exposed function

After building and installing the extension, Python can import it and call rust_json.sum('{ "name": "Rachelle Ferguson", "value": 948129 }'), which returns 948146. section 6.4

Listing 6.10 rust_json extension module that works
use pyo3::prelude::*;

#[derive(Debug, serde::Deserialize)]
struct Data {
  name: String,
  value: i32,
}

#[pyfunction]  #1
fn sum(input: &str) -> i32 {
  let parsed: Data = serde_json::from_str(input).unwrap();

  parsed.name.len() as i32 + parsed.value
}

#[pymodule]
fn rust_json(_py: Python, m: &PyModule) -> PyResult<()> {
  m.add_function(wrap_pyfunction!(sum, m)?)?;  #2

  Ok(())
}

Inspect the complete Rust extension module, including the #[pyfunction] annotation and wrap_pyfunction! registration. section 6.4

How Refactoring to Rust covers it

How deep it goes
Explains the annotation and required registration, but stops short of macro-generated wrapper internals.
Examples
Uses a sum function that parses JSON and is called from Python and a larger Python program.
What it assumes
Assumes a Rust function and PyO3 module setup, while demonstrating the Python-facing registration steps.
What you can do after
Apply it via PyO3 to expose a Rust function to Python.
How it connects
Connects PyO3 with Python extension modules, pymodule, and wrap_pyfunction!.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.