Can you write part of a library in rust (pyo3) but the rest in python?

Question:

I want to write part of a python module in rust (with PYo3) but also partly in python, so something like…

src/utils.rs:

use pyo3::prelude::*;

#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
    Ok((a + b).to_string())
}

#[pymodule]
fn nvm(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    Ok(())
}

src/main.py:

from .utils import sum_as_string

...

Mostly just curious if this is possible with pyo3 or if I have to write everything in rust, cuz I’ve seen something like this done with C/Cython (example).

Asked By: middledot

||

Answers:

Yes, this is possible. Maturin is the project you’ll want to look through for doing this as pyo3 is simply the bindings to the python runtime. You can see documentation on a mixed python/rust project here

Answered By: wannabe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.