expression

Expose a Rust function in a Python extension

PyO3 registers Rust functions in a Python extension module. The module name must match the importable extension filename; the Bound handle ties access to the attached Python interpreter lifetime. Build the cdylib for a compatible CPython interpreter and import it in an isolated test environment. The helper is defined in checked.rs. Expected lab stdout (not executed): 42 overflow rejected Common mistake: Copying a native library to another Python version or platform without checking its ABI. This is part of a multi-file lab, not a standalone playground snippet.

Formal Syntax & Structure

rust syntaxrust
#[pymodule] fn module(m: &Bound<'_, PyModule>) -> PyResult<()>

Working Example

Example Snippetrust
use pyo3::prelude::*;mod checked;#[pymodule]fn bm106_python(m: &Bound<'_, PyModule>) -> PyResult<()> {    m.add_function(wrap_pyfunction!(checked::double, m)?)?;    Ok(())}
Rust Reference