[SOLVED] How to define default for pybind11 function as parameter

Issue

This Content is from Stack Overflow. Question asked by user1091141

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; });
}


This Question was asked in StackOverflow by user1091141 and Answered by ChrisD It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?