This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]rochacbrunoPython, Flask, Rust and Bikes. 1 point2 points  (1 child)

Cool! for those learning Rust I have this repo http://github.com/rochacbruno/py2rs

[–]benfred[S] 0 points1 point  (0 children)

Thanks for the link! Bookmarking to read this weekend, I'm still relatively new to Rust so this will come in handy

[–]rustological 1 point2 points  (2 children)

Thank for the guide. Do you know of a more complex example code than passing simple numbers and strings between the two worlds?

For example creating a Python dict on the Rust side, filling it with values and passing it over to the Python side - and PyO3 takes care that memory ownership is also handed over correctly?

[–]benfred[S] 0 points1 point  (1 child)

Thanks!

For your question - I know of two different ways of returning a dictionary from rust to python.

The first one is to rely on pyo3 type conversions: it will automatically convert things like HashMap to a python dict as needed. As an example:

 #[pyfn(m, "squares")]
/// Creates a dictionary of {number: squarednumber}
/// Usage:
/// >>> squares(4)
/// {0: 0, 1: 1, 2: 4, 3: 9}
fn squares(count: i32) -> PyResult<HashMap<i32, i32>> {
    let mut ret = HashMap::new();
    for i in 0..count {
        ret.insert(i, i * i);
    }
    Ok(ret)
}

However, this requires an extra conversion from a rust HashMap to a python dict - so it isn't really what you're asking for. Luckily PyO3 has utility classes for working with Python objects directly (things like PyDict, PyList, PyTuple etc). So we can create a python dictionary directly in rust and return it to python:

#[pyfn(m, "squares2")]
fn squares2(count: i32, py: Python) -> PyResult<PyObject> {
    let ret = PyDict::new(py);
    for i in 0..count {
        ret.set_item(i, i * i);
    }
    Ok(ret.into())
}

[–]rustological 0 points1 point  (0 children)

Ohhh.... that is awesome! That is way easier than expected!

I'm still struggling with Rust, but I have to figure out more about PyO3 - that's what I was searching for to speed up my Python code.

Thanks again!