QA
Senior LevelPython

How do you build memory-safe, ultra-fast Python native extension modules in Rust using PyO3 and compile them with Maturin?

❓ Interview Prompt: Explain `PyO3` Rust crate, `#[pyfunction]`, `#[pymodule]`, compiling `.so`/`.pyd` native extensions via `Maturin`, and C-API bindings.

PyO3 allows writing memory-safe, C-speed Python native extension modules in Rust:

Workflow:

1
Annotate Rust functions with '#[pyfunction]' and modules with '#[pymodule]'.
2
'maturin develop': Compiles Rust code into standard binary C-extension wheels ('.so' on Linux, '.pyd' on Windows) importable directly into Python with zero runtime overhead!

Code Implementation Example

rust
// Rust extension using PyO3 crate
use pyo3::prelude::*;

#[pyfunction]
fn sum_numbers(a: i64, b: i64) -> PyResult<i64> {
    Ok(a + b)
}

#[pymodule]
fn my_rust_ext(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_numbers, m)?)?;
    Ok(())
}
💡Writing native Python extension modules in Rust using PyO3.
🎯 Interview Key Takeaway

Use PyO3 and Maturin to write memory-safe Rust extension modules executing at native C speeds in Python.

#PyO3#Rust#Maturin#C Extensions#Senior
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?