In Pybind it is possible to inform Python about the names of the arguments for functions:
m.def("add", &add, "A function which adds two numbers",
py::arg("i"), py::arg("j"));
(http://pybind11.readthedocs.io/en/stable/basics.html#keyword-arguments)
Is there something similar for constructors? Spyder (Anaconda) already shows the input arguments of functions by default, but for constructors the "help" only shows: (*args, **kwargs).
Yes, in exactly the same way as it is for member functions or functions :)
struct Foo {
Foo(int x, int y) {}
void bar(int a, int b) {}
};
PYBIND11_MODULE(cpp_module, m) {
py::class_<Foo>(m, "Foo")
.def(py::init<int, int>(), py::arg("x"), py::arg("y"))
.def("bar", &Foo::bar, py::arg("a"), py::arg("b"));
}
As far as I can see, there is no real difference between using py::arg
for functions, member functions or constructors, it works in the same way (including default values etc).
Overloading a function (including the constructor) is an interesting case. Since Python has no similar overloading mechanism, this is handled by pybind11. help()
will still work, but it'll show something like this:
__init__(...)
__init__(*args, **kwargs)
Overloaded function.
1. __init__(self: some_cpp.Foo, x: int, y: int) -> None
2. __init__(self: some_cpp.Foo) -> None
As you can see, __init__
itself takes (*args, **kwargs)
and this will be what is autocompleted by most IDE's. A way around this would be to use static methods as constructors, this way you can give each constructors a unique name so Python knows about this. For example, Foo Foo::from_ints(int x, int y)
and Foo Foo::from_string(std::string s)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With