PyO3 / PyO3/pyo3

Missing create python bounded method from closure

Open
#3,107 3 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

Thanks for this great package! 👏

I'm implementing dynamic generated heap class with pyo3 in rust for an ORM.

Assign a PythonCFunction to a class won't make it behave like a method. This is different from Python methods which has a __get__ method to bound.

This will not work

let my_method = PyCFunction::new_method_closure(py, cls, Some(function_name), Some("Represent."), |args, kwargs| {
    ...
})?;
my_class.setattr(py, "my_method", my_method)?;

When accessing, the my_method is not bounded. Self is not passed in as the first argument.

There are no args passed

let my_method = PyCFunction::new_method_closure(py, cls, Some(function_name), Some("Represent."), |args, kwargs| {
    println!("see args: {:?} {:?}", args, kwargs) // (,) and None
})?;
my_class.setattr(py, "my_method", my_method)?;

After digging into some details of the implementation, I found that something like this with trampolines need to be implemented

    pub const fn cmethod_function_with_keywords(
        name: &'static str,
        cfunction: PyCMethod,
        doc: &'static str,
    ) -> Self {
        Self {
            ml_name: name,
            ml_meth: PyMethodType::PyCMethod(cfunction),
            ml_flags: ffi::METH_VARARGS | ffi::METH_KEYWORDS | ffi::METH_METHOD,
            ml_doc: doc,
        }
    }

However, I'm not skilled and able to do this. I need your help. 😃

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 by reading PyCFunction::new_method_closure and the cmethod_function_with_keywords example in the issue, including PyMethodType and the METH_VARARGS, METH_KEYWORDS, and METH_METHOD flags. Trace how the closure is installed on a class and confirm that accessing it passes the instance as the first argument, including keyword arguments.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
api, backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.