Search code examples
c++pybind11

Pybind11: How to assign default value for a struct member variable?


I am trying to create python bindings for the below

struct example {
  int a = 1;
  int b = 2;
};

This is what I have so far

PYBIND11_MODULE(example_python, m) {
   py::class_<example>(m, "example")
    .def_readwrite("a", &example::a)
    .def_readwrite("b", &example::b);
}

when I checked in python, both a and b are empty, so I tried something like

PYBIND11_MODULE(example_python, m) {
   py::class_<example>(m, "example")
    .def_readwrite("a", &example::a, py::arg("a") = 1)
    .def_readwrite("b", &example::b, py::arg("b") = 2);
}

but this results in a compilation error. I went through the documentation multiple times but couldn't a way to do it. Can someone let me know how to assign the default values in pybind11?


Solution

  • Your code doesn't compile, at least on my machine, because you didn't bind any constructor. However, if you do so then the default values become populated (because that's part of what a constructor does!). In other words, just use this:

    PYBIND11_MODULE(example_python, m) {
       py::class_<example>(m, "example")
        .def(py::init<>()) // <-- bind the default constructor
        .def_readwrite("a", &example::a)
        .def_readwrite("b", &example::b);
    }