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
