On this page
  1. PyO3
  2. Contents
  3. Overview & Cargo.toml Setup
  4. Exposing Functions, Classes & Errors
  5. Python<'py>, Bound<'py, T> & Releasing the GIL

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

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

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

Linked from

Related notes