Skip to content
Advertisement

Why does pybind fail for functions without arguments?

I have an overloaded constructor in C++ (default + other). My automatically generated pybind code looks like this:

    py::class_<MyClass>(m, "MyClass")
        .def(
            py::init<>(),
            py::kw_only()
        )
        .def(
            py::init<
                std::valarray<std::string>
            >(),
            py::kw_only(),
            py::arg("my_var")
        )

When I delete the first constructor everything works fine. But for the first one I get this error:

error: static assertion failed: py::kw_only requires the use of argument annotations
static_assert(has_arg_annotations || !has_kw_only_args, 
"py::kw_only requires the use of argument annotations"

Does anyone know why this error is coming up and how to fix it?

Edit: I am using a custom pybind generator.

Advertisement

Answer

Thanks @463035818_is_not_a_number for pointing me in the right direction. I was confused cause I mixed up kw_only with **kwargs. kw_only means, that only named arguments are allowed when calling a function which doesn’t make sense without arguments.

My custom pybind generator added kw_only to all functions and the build failed because of that. As a solution I added an if-condition to check whether there are function arguments and only added kw_only if there are any:

if (args.size() > 0) { out << "n"; 
out << ">()," << "n"
    << "py::kw_only()";}
else {
    out << ">()";
}

The generated pybind code looks like this:

    py::class_<MyClass>(m, "MyClass")
        .def(
            py::init<>()
        )
        .def(
            py::init<
                std::valarray<std::string>
            >(),
            py::kw_only(),
            py::arg("my_var")
        )
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement