Create python bindings for a rust crate

I have a rust crate (Musixmatch)[https://crates.io/crates/musixmatch] and I would like to create python bindings for it. So to create bindings one needs to use pyo3.rs.
However it returns PyResult... Is there a way to create the bindings for python but I want to keep the rust crate useable via rust without any issues.
(Btw , idk if this helps but I plan to create bindings in many längs like JS, python,java and kotlin )

1 Like

I have 2 solutions in mind:

  • keep the normal API and have additional python bindings and pyo3 dependency hidden behind a feature flag
  • leave your current crate as is and make a second wrapper crate to provide python bindings (musixmatch-pyrs or something)
Example 1
// lib.rs
#[cfg(feature = "python")]
mod py_api; // write all your python wrappers here
#[cfg(feature = "python")]
pub use py_api::*;
2 Likes

There's no rule that says that you have to make your core Rust functions return PyResult. Keep your domain error type as-is, and create separate, thin wrappers of which the purpose is specifically to talk to Python.

3 Likes

So if I understood your reply correctly , I should do something like

pub fn etwas() -> u8  {
....
}
// So then for python bindings 
#[pyfunction]
fn etwas() -> usize {
   ....
}
//Or
#[cfg(feature = "python")]
#[pyfunction(name = "etwas")]
fn py_etwas() -> u8 {
//.... 

So in the 1. case I can just add #[pyfunction] on top of my rust function and it works..

But in either case I need to create a #[pymodule] function right eg :

#[pymodule]
/// A Python module implemented in Rust.
fn string_sum(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pyfunction!(etwas))?;
    Ok(())
}

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.