PyO3 / pyo3

Rust bindings for the Python interpreter
https://pyo3.rs
Other
11.81k stars 725 forks source link

Quality of life macro for generic functions #3865

Open iliya-malecki opened 6 months ago

iliya-malecki commented 6 months ago

Hello there! im currently using something like this in my project (please ignore the specifics, i want to share the general idea without ripping it out of the context that sparked the idea):

macro_rules! concrete_ordinal_encoding {
    ($typename: ident, $pymodule: ident) => {
        paste::item! {
            #[pyfunction]
            fn [< ordinal_encoding_$typename >]<'py>(py: Python<'py>, labels: Vec<$typename>) -> &'py PyArray1<usize> {
                ordinal_encoding(labels).into_pyarray(py)
            }
            $pymodule.add_function(wrap_pyfunction!([< ordinal_encoding_$typename >], $pymodule)?)?;
        }
    };
}

So, naturally, i wondered: is it a good idea to turn it into some sort of concrete_function!() macro to specialize generic functions to interface with python? on the python side, it could be implemented with an object with __getitem__ or __getattr__ to resolve what specific function to call. Do you think it is worth a dependency? Do you think this approach smells nice enough to be included in pyo3?

davidhewitt commented 6 months ago

Hello! Sorry to have been slow to reply.

This is an interesting idea, here's a few of my initial reactions:

Dan-wanna-M commented 2 months ago

I think we probably want the python side to have a 'generic' function which dispatches to Rust binding function. Otherwise, I feel like we are not really saving much boilerplates. This is also closer to 'generic' semantics. This naturally means we want to monophize for every type parameter as well. I am not sure whether publicly exposing these monophizations yo Pytjon is a good idea though.