Darko
Darko

Reputation: 609

What is the best way to check of an object is an Enum in Cython?

I am looking for a Cythonic way (yes, Cython) to check if an object is of type Enum. Specifically, I want to distinguish between ints and IntEnums. I am looking for something like:

cdef extern from "Python.h":
    bint PyObject_TypeCheck(object obj, PyTypeObject* type) nogil

PyObject_TypeCheck(obj, &PyEnumType_Type)

But, is there something like PyEnumType_Type defined anywhere?

Upvotes: 1

Views: 247

Answers (3)

Darko
Darko

Reputation: 609

Yet a third way that does not require importing Enum into Cython.

if getattr(val, 'name', None) is not None

Upvotes: 0

Darko
Darko

Reputation: 609

Regular old isinstance(obj, Enum) works fine in Cython as well, but does it have good performance? Maybe I am overthinking this.

Upvotes: 1

Darko
Darko

Reputation: 609

I think I may have found what I am looking for. There is a PyEnum_Type defined in cpython/include/enumobject.h. I will try the following:

cdef extern from "Python.h":
    PyTypeObject PyEnum_Type
    bint PyObject_TypeCheck(object obj, PyTypeObject* type) nogil

PyObject_TypeCheck(obj, &PyEnum_Type)

Upvotes: 0

Related Questions