How to call Rust functions from Python code in JupyterLab
Published in
2 min readDec 10, 2023
Python is an important tool in any bioinformatician’s toolkit. My goal is to help you add Rust in this toolkit rather than replace Python. Here is a way to make sure your two tools can talk to each other.
Step 1: Install maturin (Rust crate)
cargo install maturin
Step 2: Create a new Rust project and add pyo3. Or add this dependency to an existing project.
cargo new rusty_python --lib
// Add this in Cargo.toml file
[dependencies]
pyo3 = { version = "0.20", features = ["extension-module"] }
Step 3: Write new Rust functions that will be called from Python or modify existing ones.
// Example lib.rs file
use pyo3::prelude::*;
#[pyfunction]
fn gc_content(seq: &str) -> PyResult<f32> {
let mut length = 0;
let mut count = 0;
for base in seq.chars() {
length += 1;
if base == 'G' || base == 'C' {
count += 1;
}
}
Ok(count as f32 / length as f32)
}
// This function name should be same as your project name
#[pymodule]
fn rusty_python(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(gc_content, m)?)?;
Ok(())
}
Step 4: Let maturin do its magic
Run the following command within your Rust project (inside rusty_python directory).
maturin develop
Step 5: Call your Rust function from Python
from rusty_python import gc_content
dna_sequence = "ACTG"
gc_content(dna_sequence)
# Output: 0.5
Next Steps
- See the Jupyter notebook that calls Rust from Python
- See the Rust project with a function designed to work with Python