CpdefEnums.pyx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #################### EnumBase ####################
  2. cimport cython
  3. cdef extern from *:
  4. int PY_VERSION_HEX
  5. cdef object __Pyx_OrderedDict
  6. if PY_VERSION_HEX >= 0x02070000:
  7. from collections import OrderedDict as __Pyx_OrderedDict
  8. else:
  9. __Pyx_OrderedDict = dict
  10. @cython.internal
  11. cdef class __Pyx_EnumMeta(type):
  12. def __init__(cls, name, parents, dct):
  13. type.__init__(cls, name, parents, dct)
  14. cls.__members__ = __Pyx_OrderedDict()
  15. def __iter__(cls):
  16. return iter(cls.__members__.values())
  17. def __getitem__(cls, name):
  18. return cls.__members__[name]
  19. # @cython.internal
  20. cdef object __Pyx_EnumBase
  21. class __Pyx_EnumBase(int):
  22. __metaclass__ = __Pyx_EnumMeta
  23. def __new__(cls, value, name=None):
  24. for v in cls:
  25. if v == value:
  26. return v
  27. if name is None:
  28. raise ValueError("Unknown enum value: '%s'" % value)
  29. res = int.__new__(cls, value)
  30. res.name = name
  31. setattr(cls, name, res)
  32. cls.__members__[name] = res
  33. return res
  34. def __repr__(self):
  35. return "<%s.%s: %d>" % (self.__class__.__name__, self.name, self)
  36. def __str__(self):
  37. return "%s.%s" % (self.__class__.__name__, self.name)
  38. if PY_VERSION_HEX >= 0x03040000:
  39. from enum import IntEnum as __Pyx_EnumBase
  40. #################### EnumType ####################
  41. #@requires: EnumBase
  42. cdef dict __Pyx_globals = globals()
  43. if PY_VERSION_HEX >= 0x03040000:
  44. # create new IntEnum()
  45. {{name}} = __Pyx_EnumBase('{{name}}', __Pyx_OrderedDict([
  46. {{for item in items}}
  47. ('{{item}}', {{item}}),
  48. {{endfor}}
  49. ]))
  50. {{for item in items}}
  51. __Pyx_globals['{{item}}'] = {{name}}.{{item}}
  52. {{endfor}}
  53. else:
  54. class {{name}}(__Pyx_EnumBase):
  55. pass
  56. {{for item in items}}
  57. __Pyx_globals['{{item}}'] = {{name}}({{item}}, '{{item}}')
  58. {{endfor}}