PyO3 / PyO3/pyo3

Add partial generic support in pyfunctions

Open
#5,076 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

Hi,

I am currently developing a crate that export a generic function that is meant to be configured by users at compile time before being exported to python. This looks like this:

trait Config {
    const KEY: [u8; 32];
}

pub fn encrypt<C: Config>(data: &[u8]) -> Vec<u8> {
    // use C::KEY here to encrypt the data  
}

Then the user of that crate would export that function in their python module using wrap_pyfunction! macro.

Currently, this is not possible. I have to export a declarative macro that will construct that function in the user's module, so that it can avoid the generic and use C directly.

Would you accept a PR that will modify the pyfunction proc macro and the wrap_pyfunction! declarative macro to support generics, where the user has to define the name + all the generics of the function in the wrap_pyfunction macro if the function is generic?

This would look like that:

trait Config {
    const KEY: [u8; 32];
}

#[pyfunction]
pub fn encrypt<C: Config>(data: &[u8]) -> Vec<u8> {
    // use C::KEY here to encrypt the data  
}

// -- in user crate --

struct Conf;

impl Config for Conf {
    const KEY: [u8; 32] = [0; 32];
}

#[pymodule]
fn module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!("encrypt", encrypt, Conf)?)
}

(The exact syntax can be changed)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the pyfunction proc macro and wrap_pyfunction! declarative macro named in the issue, then trace how a function is converted and registered. Done means a generic #[pyfunction] can be registered with the function name and concrete generic arguments, with the accepted syntax settled.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
api, devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.