PyO3: best way to return bytes from function call?

Using the latest PyO3, given some function which returns a bunch of bytes, like:

#[pyfunction]
fn some_bytes() -> Vec<u8> {
    vec[1,2,3]
}

When called on the Python side, it returns a list of integers, like:

>>> some_bytes()
[1, 2, 3]

What's the most straightforward way to have the function return a (binary) bytes object? Like:

>>> some_bytes()
b'\x01\x02\x03'

It seems like it should be a trivial conversion, but I've just started with PyO3 and the documentation has me stumped. Any help would be appreciated!

I guess you have to explicit about the Python side type:

https://docs.rs/pyo3/0.11.1/pyo3/types/struct.PyBytes.html#method.new

use pyo3::types::PyBytes;

#[pyfunction]
fn some_bytes(py: Python) -> PyBytes {
    let data = vec![1, 2, 3];
    PyBytes::new(py, &data)
}
1 Like

That one almost works, but it's definitely a step in the right direction. Turns out the compiler doesn't like PyBytes as a return type, but a slight adjustment:

use pyo3::types::PyBytes;

#[pyfunction]
fn some_bytes(py: Python) -> PyObject {
    let data = vec![1, 2, 3];
    PyBytes::new(py, &data).into()
}

compiles properly and works as expected.

Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.