On this page
PyO3
Prev: third_party/rust | Up: third_party/rust | Next: Maturin
Rel: Maturin, Rust & Python (PyO3 + Maturin), unsafe Rust & C ABI FFI, Python FFI
Ref: PyO3 User Guide
Tags: #public #prog #rust #python3 #third-party #ffi #tier/core
Contents
- > Overview & `Cargo.toml` Setup
- > Exposing Functions, Classes & Errors
- > `Python<'py>`, `Bound<'py, T>` & Releasing the GIL
Overview & Cargo.toml Setup
PyO3 generates safe, ergonomic Rust bindings to the CPython C API, letting you write native Python extension modules in Rust (built and packaged with Maturin).
[lib]
name = "fast_ext"
crate-type = ["cdylib"]
[dependencies]
pyo3 = { version = "0.24", features = ["extension-module"] }
Exposing Functions, Classes & Errors
#[pyfunction]exports a Rust function;PyResult<T>maps RustErrcleanly to Python exceptions (PyValueError,PyRuntimeError).#[pyclass]/#[pymethods]exposes a Rust struct as a native Python class.#[pymodule]registers the extension module imported by Python.
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
#[pyfunction]
fn sum_squares(nums: Vec<i64>) -> i64 {
nums.iter().map(|n| n * n).sum()
}
#[pyclass]
struct Counter {
#[pyo3(get)]
value: i64,
}
#[pymethods]
impl Counter {
#[new]
fn new(start: i64) -> PyResult<Self> {
if start < 0 {
return Err(PyValueError::new_err("start must be non-negative"));
}
Ok(Self { value: start })
}
fn inc(&mut self, step: i64) {
self.value += step;
}
}
#[pymodule]
fn fast_ext(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_squares, m)?)?;
m.add_class::<Counter>()?;
Ok(())
}
Python<'py>, Bound<'py, T> & Releasing the GIL
- Accepting
py: Python<'py>proves the current thread holds the CPython GIL; Python objects are accessed through lifetime-boundBound<'py, T>handles. - For CPU-heavy Rust loops, release the GIL via
py.allow_threads(|| ...)(orpy.detach(|| ...)in newer PyO3) so other Python threads run concurrently.
Linked from
Related notes
- tuts/rust/ownership_and_internals/unsafe_rust_and_ffi_abi Linked here; links to this page; shared tags: #ffi, #prog, #rust
- tuts/third_party/python3/maturin Linked here; links to this page; shared tags: #prog, #rust, #tier
- tuts/interop/rust_and_python_pyo3_maturin Linked here; links to this page; shared tags: #prog, #rust
- tuts/third_party/rust Linked here; links to this page; shared tags: #prog, #rust
- tuts/rust links to this page; shared tags: #prog, #rust
- tuts/rust/cargo_and_tooling links to this page; shared tags: #prog, #rust
- tuts/rust/cargo_and_tooling/cargo_workspaces_and_profiles links to this page; shared tags: #prog, #rust
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces Linked here; shared tags: #ffi
- tuts/rust/std/ffi/CString shared tags: #ffi, #prog, #rust, #tier
- tuts/rust/std/ffi/extern_C shared tags: #ffi, #prog, #rust, #tier