On this page
  1. Rust & Python via PyO3 + Maturin
  2. Contents
  3. When to Use PyO3 + Maturin vs. ctypes
  4. 1. Rust Implementation (src/lib.rs) with GIL Release
  5. 2. Python Type Stub (python/fast_ext/_native.pyi)
  6. 3. Build & Call from Python

Rust & Python via PyO3 + Maturin

Prev: interop | Up: interop | Next: C & Python via ctypes
Rel: PyO3, Maturin, Cargo Workspaces & Profiles, Python FFI
Ref: PyO3 User Guide | Maturin User Guide
Tags: #public #prog #interop #rust #python3 #pyo3 #maturin #tutorials


Contents


When to Use PyO3 + Maturin vs. ctypes

Approach Dependencies Strengths
ctypes + C Pure stdlib Calling existing OS/C shared libraries with zero build tooling
PyO3 + Maturin pyo3, maturin Native Python classes, automatic Result -> exception mapping, safe GIL release, distributable wheels

1. Rust Implementation (src/lib.rs) with GIL Release

Release the GIL during CPU-bound loops so multi-threaded Python callers scale across CPU cores:

use pyo3::prelude::*;

#[pyfunction]
fn count_primes(py: Python<'_>, limit: u64) -> u64 {
    py.allow_threads(|| {
        (2..limit)
            .filter(|&n| {
                let root = (n as f64).sqrt() as u64;
                (2..=root).all(|d| n % d != 0)
            })
            .count() as u64
    })
}

#[pymodule]
fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(count_primes, m)?)?;
    Ok(())
}

2. Python Type Stub (python/fast_ext/_native.pyi)

Provide a .pyi stub alongside the compiled extension so static type checkers and editors know exact signatures:

def count_primes(limit: int) -> int: ...

3. Build & Call from Python

python3 -m venv .venv && source .venv/bin/activate
pip install maturin
maturin develop --release
python3 -c "import fast_ext; print(fast_ext.count_primes(100_000))"

Linked from

Related notes