Search code examples
pythonenumscythoncpython

Defining enums in Cython code that will be used in the C part of code


I have defined and enum in cython header file api.pxd:

ctypedef enum InstructionType:
    default = 0
    end_if = 1
    end_loop = 2
    backward_jump_here = 4

I also have checked if turning ctypedef to cdef would work (and it didn't).

And I want to use value from this enum in __cinit__ method fo some class:

from api cimport Instruction, CLinVM, InstructionType

# (...) some other classes

cdef class EndIf(Noop):
   def __cinit__(self):
      self.type = InstructionType.end_if

And I get compilation error:

    self.type = InstructionType.end_if
                              ^
------------------------------------------------------------
 /home/(...)/instructions.pyx:149:35: 'InstructionType' is not a constant, 

Any way to define and use enum in such way?


Solution

  • You do not access enumerated constants through their typename they belong to, neither in C, nor in C++, nor in Cython. You'd need to create a wrapper .pxd for it.