10

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?

Richard
  • 56,349
  • 34
  • 180
  • 251
  • Have you tried without calling export_values()? works for me – ZivS Jan 10 '18 at 20:18
  • same problem here. I think in this situation a "unscoped enum" is a better fit: https://github.com/pybind/pybind11/blob/master/tests/test_enum.cpp but I still get the "incompatible function arguments" type error. – moin moin Feb 06 '18 at 08:34

1 Answers1

8

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");
}
moin moin
  • 2,263
  • 5
  • 32
  • 51