-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.

3
  • 1
    Provide a minimal reproducible example. Commented Sep 6, 2022 at 9: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? Commented Sep 6, 2022 at 9: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. Commented Sep 6, 2022 at 10:32

1 Answer 1

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")
        )
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I edited my question and my answer, I hope it is clear now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.