Advertisement
dan-masek

dan-masek Adding support for len in pybind11 enum -- version 2

Jul 13th, 2023
1,200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. #include <pybind11/pybind11.h>
  2.  
  3. namespace py = pybind11;
  4.  
  5. enum class Kind { Kind1 = 1, Kind2, Kind3 };
  6.  
  7.  
  8. py::object get_pybind11_metaclass()
  9. {
  10.     auto &internals = py::detail::get_internals();
  11.     return py::reinterpret_borrow<py::object>((PyObject*)internals.default_metaclass);
  12. }
  13.  
  14. py::object get_standard_metaclass()
  15. {
  16.     auto &internals = py::detail::get_internals();
  17.     return py::reinterpret_borrow<py::object>((PyObject *)&PyType_Type);
  18. }
  19.  
  20. py::object create_enum_metaclass()
  21. {
  22.     auto pybind11_metaclass = get_pybind11_metaclass();
  23.     auto standard_metaclass = get_standard_metaclass();
  24.  
  25.     py::dict attributes;
  26.     attributes["__len__"] = py::cpp_function(
  27.         [](py::object cls) {
  28.             return py::len(cls.attr("__entries"));
  29.         }
  30.         , py::is_method(py::none())
  31.         );
  32.     return standard_metaclass(std::string("pybind11_ext_enum")
  33.         , py::make_tuple(pybind11_metaclass)
  34.         , attributes);
  35. }
  36.  
  37. PYBIND11_MODULE(so07, m)
  38. {
  39.     auto enum_metaclass = create_enum_metaclass();
  40.     py::enum_<Kind>(m, "Kind", py::metaclass(enum_metaclass))
  41.         .value("Kind1", Kind::Kind1)
  42.         .value("Kind2", Kind::Kind2)
  43.         .value("Kind3", Kind::Kind3)
  44.         ;
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement