Search code examples
pythonc++pybind11

Pybind11 - Function with unknown number of arguments


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?


Solution

  • 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.