Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyBind11 Global-Level Enum

The PyBind11 documentation talks about using enum here.

The example shown assumes that the enum is embedded within a class, like so:

struct Pet {
    enum Kind {
        Dog = 0,
        Cat
    };

    Pet(const std::string &name, Kind type) : name(name), type(type) { }

    std::string name;
    Kind type;
};

py::class_<Pet> pet(m, "Pet");

pet.def(py::init<const std::string &, Pet::Kind>())
    .def_readwrite("name", &Pet::name)
    .def_readwrite("type", &Pet::type);

py::enum_<Pet::Kind>(pet, "Kind")
    .value("Dog", Pet::Kind::Dog)
    .value("Cat", Pet::Kind::Cat)
    .export_values();

My situation is different. I have a global enum the value of which is used to alter the behaviour of several functions.

enum ModeType {
  COMPLETE,
  PARTIAL,
  SPECIAL
};

std::vector<int> Munger(
  std::vector<int> &data,
  ModeType          mode
){
  //...
}

I have tried to register it like so:

PYBIND11_MODULE(_mlib, m) {
  py::enum_<ModeType>(m, "ModeType")
    .value("COMPLETE", ModeType::COMPLETE )
    .value("PARTIAL",  ModeType::PARTIAL  )
    .value("SPECIAL",  ModeType::SPECIAL  )
    .export_values();

  m.def("Munger",              &Munger, "TODO");
}

Compilation is successful and the module loads in Python, but I do not see ModeType in the module's names.

What can I do?

like image 789
Richard Avatar asked Dec 19 '17 19:12

Richard


1 Answers

the sample below works for me. Like in my comment I used an "unscoped enum" (github.com/pybind/pybind11/blob/master/tests/test_enum.cpp).

I can use it like this

import pybind11_example as ep
ep.mood(ep.Happy)

code:

#include <pybind11/pybind11.h>

enum Sentiment {
    Angry = 0,
    Happy,
    Confused
};

void mood(Sentiment s) {
};

namespace py = pybind11;

PYBIND11_MODULE(pybind11_example, m) {
    m.doc() = "pybind11 example";

    py::enum_<Sentiment>(m, "Sentiment")
        .value("Angry", Angry)
        .value("Happy", Happy)
        .value("Confused", Confused)
        .export_values();

    m.def("mood", &mood, "Demonstrate using an enum");
}
like image 175
moin moin Avatar answered Oct 04 '22 14:10

moin moin