Search code examples
c++pybind11

How to define default for pybind11 function as parameter


As per the pybind documentation, we can pass a function from Python to C++ via the following code:

#include <pybind11/pybind11.h>
#include <pybind11/functional.h>

int func_arg(const std::function<int(int)> &f) {
    return f(10);
}

PYBIND11_MODULE(example, m) {
    m.def("func_arg", &func_arg);
}

How can we define a default function int -> 1 that is used for f if no parameter is passed?

$ python
>>> import example
>>> example.func_arg() # should return 1

Solution

  • One possibility is

    namespace py = pybind11;
    
    int func_arg(const std::function<int(int)> &f) {
        return f(10);
    }
    
    std::function<int(int)> default_func = [](int) -> int { return 1; };
    
    PYBIND11_MODULE(example, m) {
        m.def("func_arg", &func_arg, py::arg("f")=default_func);
    }
    

    An even simpler one is just overload the func_arg wrapper itself

    PYBIND11_MODULE(foo, m) {
        m.def("func_arg", &func_arg);
        m.def("func_arg", [](void) -> int { return 1; });
    }