Using a Python 2.7 enum from C
I have an enum in Python (backported enum package to 2.7) that is meant to be of only integers:
import enum class MyEnum(enum.Enum): val = 0
Let's say I receive a PyObject * in a C extension pointing to MyEnum.val. I want the integer value associated with the PyObject *. How do I get it most succinctly?
So, you just use PyObject_GetAttr and friends to access class attributes. In particular, if you have a MyEnum.val, you need to get its value attribute, which will be an int, which you can then PyInt_AsLong.
This is the same way things work in Python. If you try to use MyEnum.val where an int is expected, you should get a TypeError; if you try to explicitly call int(MyEnum.val), you will definitely get a TypeError. So, although I haven't tested it, PyInt_AsLong directly on the constant instead of its value should raise a TypeError and return -1.
If you want enumeration constants that act like subtypes of int, then, as the enum docs explain, you want IntEnum. Usually, that isn't really what you want (as the docs explain), but if it is, of course it works. And you should be able to PyInt_Check and PyInt_AsLong an IntEnum value (although, again, I haven't tested).