Home > front end >  Pybind11 - Function with unknown number of arguments
Pybind11 - Function with unknown number of arguments

Time:06-18

I want to get a list of arguments

my current c code:

m.def("test", [](std::vector<pybind11::object> args){
    return ExecuteFunction("test", args);
});

my current python code:

module.test(["-2382.430176", "-610.183594", "12.673874"])
module.test([])

I want my python code to look like this:

module.test("-2382.430176", "-610.183594", "12.673874")
module.test()

How can I get all arguments passed through Python?

CodePudding user response:

Such generic functions module.test(*args) can be created using pybind11:

void test(py::args args) {
    // do something with arg
}

// Binding code
m.def("test", &test);

Or

m.def("test", [](py::args args){
    // do something with arg
});

See Accepting *args and **kwargs and the example for more details.

CodePudding user response:

m.def("test", [](const pybind11::args& args){
    std::vector<pybind11::object> pyArgs;
    for (const auto &arg : args) {
        pyArgs.push_back(arg.cast<pybind11::object>());
    }
    return ExecuteFunction("test", pyArgs);
});

CodePudding user response:

I have to admit I'm not entirely sure what you're trying to do, but here is one idea:

def wrapper(args*)
    return module.test(args)

There are other ways of making such a wrapper but this should work if I understand your question correctly.

  • Related