How to Call Rust from Python (PyO3, rust-cpython)

Use PyO3 with Maturin to compile Rust functions into a Python-importable shared library for high-performance integration.

Use PyO3 to compile Rust code into a shared library that Python can import as a native module.

  1. 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

  2. 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`

  1. Build the shared library for your current Python version. maturin develop

  2. Import and call the function in your Python script. python -c "import my_rust_module; print(my_rust_module.greet('World'))"