Search code examples
pythonc++pybind11

How to set just one default argument pybind11


I have a function :

void my_functions(int a, int b = 42);

And I want to bind it using only the default argument for b:

 m.def("my_functions", &my_functions, pb::arg("b") = 42); // just default for b

This doesn't work, I get:

/cache/venv/include/pybind11/pybind11.h:219:40: error: static assertion failed: The number of argument annotations does not match the number of function arguments
  219 |             expected_num_args<Extra...>(
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
  220 |                 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),

What's the right way of doing it?


Solution

  • This is how:

    m.def("my_functions", &my_functions, pb::arg(), pb::arg("b") = 42)
    

    See here: https://pybind11.readthedocs.io/en/stable/advanced/functions.html#non-converting-arguments

    When specifying py::arg options it is necessary to provide the same number of options as the bound function has arguments. …