How to Build High‑Performance Python Extensions with Rust (Step‑by‑Step Guide)
Learn how to create native Python extension modules using Rust, set up the required tools, write and build the Rust code, and run Python scripts from a Rust binary, enabling you to combine Rust's performance and safety with Python's flexibility.
In modern software development, integrating Rust and Python is increasingly common. Rust offers efficient and safe low‑level system programming, while Python provides a concise syntax and a powerful library ecosystem. Combining them lets you enjoy performance and memory safety alongside flexibility and rapid development.
Creating a Rust Python Extension Module
Install Required Tools
First, install the necessary tools:
Install Rust and Cargo: Rust's package manager.
Install maturin : A tool for building and publishing Python packages that supports generating Rust extension modules.
Install Python 3.x: Ensure Python is installed and available in your environment path.
<code># Install maturin
pip install maturin</code>Create a Rust Project
Create a new Rust library project:
<code>cargo new --lib my_rust_extension
cd my_rust_extension</code>Add the following dependencies to Cargo.toml :
<code>[package]
name = "my_rust_extension"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies.pyo3]
version = "0.16"
features = ["extension-module"]</code>Write the Extension Module
Edit src/lib.rs and add:
<code>use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
/// A simple function that adds two numbers and returns the result as a string
#[pyfunction]
fn sum_as_string(a: i32, b: i32) -> PyResult<String> {
Ok((a + b).to_string())
}
/// Define the Python module
#[pymodule]
fn my_rust_extension(py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
Ok(())
}
</code>Build the Extension Module
Use maturin to build and install the module into your Python environment:
<code>maturin develop</code>Test the module from Python:
<code>import my_rust_extension
result = my_rust_extension.sum_as_string(3, 4)
print(result) # Output: "7"
</code>Running and Interacting with Python Code from a Rust Binary
Use the cpython Crate
Add the cpython dependency:
<code>[dependencies]
cpython = "0.6.0"
</code>Write Rust Code
Edit src/main.rs with the following example:
<code>use cpython::{Python, PyResult, PyObject, PyDict};
fn main() -> PyResult<()> {
let gil = Python::acquire_gil();
let py = gil.python();
// Run a simple Python statement
py.run("print('Hello from Python!')", None, None)?;
// Call a Python function and get its return value
let sys = py.import("sys")?;
let version: String = sys.get("version")?.extract()?;
println!("Python version: {}", version);
// Use Python code to compute
let locals = PyDict::new(py);
locals.set_item(py, "a", 2)?;
locals.set_item(py, "b", 3)?;
py.run("c = a + b", None, Some(&locals))?;
let result: i32 = locals.get_item(py, "c").unwrap().extract(py)?;
println!("Result of a + b: {}", result);
Ok(())
}
</code>Build and Run the Rust Binary
Build the project:
<code>cargo build</code>Run the generated binary:
<code>./target/debug/my_rust_extension</code>Expected output:
<code>Hello from Python!
Python version: 3.x.x
Result of a + b: 5
</code>Conclusion
These two sections demonstrate how to create a native Python extension module with Rust and how to run and interact with Python code from a Rust binary. Combining Rust and Python lets you leverage the strengths of both languages to build powerful and efficient applications.
Whether you want to use Rust to accelerate performance‑critical parts of a Python project or to embed Python's extensive libraries within a Rust application, these techniques can help you achieve your goals.
Architecture Development Notes
Focused on architecture design, technology trend analysis, and practical development experience sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.