pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.32k stars 2.07k forks source link

Support for dataclasses #2065

Open quicknir opened 4 years ago

quicknir commented 4 years ago

pybind11 talks of course about how to wrap C++ classes so that they are accessible in python. The issue for me is that on the python side of things, we are using dataclasses very extensively. They provide a lot of useful built in features as well as type annotations that you can use with mypy. If you are wrapping a C++ class, then obviously, all the types are already present, so in principle it would be possible at no extra cost to export a dataclass rather than a regular python class, which would be really useful.

Maybe this is not possible to do from a purely C/C++ module, but if it is it would be pretty amazing.

liff-engineer commented 4 years ago

Same problem for me. IMO dataclasses is a decorator, I try to implement like this:

auto dataclass = py::module::import("dataclasses").attr("dataclass");
py::class_<MyClass>  myClass(m,"MyClass");
//class members export

//decorate MyClass by dataclass decorator
m.attr("MyClass")=dataclass(m.attr("MyClass"));

But failed because some thing like "init instance".

There should be a way to implement, maybe I missed something.