Use PyO3 to compile Rust code into a shared library that Python can import as a native module.
-
Create a new Rust library project and add PyO3 as a dependency.
cargo new --lib my_rust_module && cd my_rust_module && cargo add pyo3 --features extension-module -
Write the Rust function with the
#[pyfunction]attribute and expose it via#[pymodule]. `cat > src/lib.rs << 'EOF' use pyo3::prelude::*;
#[pyfunction] fn greet(name: &str) -> String { format!("Hello, {}!", name) }
#[pymodule] fn my_rust_module(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(greet, m)?)?; Ok(()) } EOF`
-
Build the shared library for your current Python version.
maturin develop -
Import and call the function in your Python script.
python -c "import my_rust_module; print(my_rust_module.greet('World'))"