expression

Translate Rust failure into Python exceptions

A Python-callable Rust function can return PyResult instead of panicking. Checked arithmetic in this example maps overflow within i32 to ValueError. Conversion of a Python integer that does not fit i32 can fail before the function body executes, so the two failures are distinct. Expected lab stdout (not executed): 42 overflow rejected Common mistake: Using unchecked arithmetic or unwrap to handle a user-supplied Python integer. This is part of a multi-file lab, not a standalone playground snippet.

Formal Syntax & Structure

rust syntaxrust
#[pyfunction] fn f(...) -> PyResult<T>

Working Example

Example Snippetrust
use pyo3::{exceptions::PyValueError, prelude::*};#[pyfunction]pub fn double(input: i32) -> PyResult<i32> {    input.checked_mul(2).ok_or_else(|| PyValueError::new_err("result outside i32 range"))}
Rust Reference