On this page
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`
- > 1. Rust Implementation (`src/lib.rs`) with GIL Release
- > 2. Python Type Stub (`python/fast_ext/_native.pyi`)
- > 3. Build & Call from Python
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
- tuts/interop Linked here; links to this page; shared tags: #interop, #prog
- tuts/third_party/python3/maturin Linked here; links to this page; shared tags: #prog, #rust
- tuts/third_party/rust/pyo3 Linked here; links to this page; shared tags: #prog, #rust
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces Linked here; links to this page; shared tags: #tutorials
- tuts/rust/tutorials links to this page; shared tags: #prog, #rust, #tutorials
- tuts/c/tutorials/c_shared_library_with_python_ctypes Linked here; shared tags: #prog, #tutorials
- tuts/interop/java_and_c_ffm_and_jni links to this page; shared tags: #interop, #prog
- tuts/rust links to this page; shared tags: #prog, #rust
- tuts/rust/cargo_and_tooling/cargo_workspaces_and_profiles Linked here; shared tags: #prog, #rust
- tuts/third_party/rust links to this page; shared tags: #prog, #rust