-2

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.

thzu
  • 23
  • 1
  • 4
  • 1
    Provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Jason Sep 06 '22 at 09:07
  • I am not into this, but after reading docs I beleive `py::kw_only()` only makes sense when there are arguments. Why do you want `py::kw_only()` on a default constructor? – 463035818_is_not_an_ai Sep 06 '22 at 09:20
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 06 '22 at 10:32

1 Answers1

0

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")
        )
thzu
  • 23
  • 1
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 19 '22 at 11:05
  • I edited my question and my answer, I hope it is clear now. – thzu Sep 27 '22 at 07:57