9
10
11 class EnumClass(object):
12 __slots__ = names
13 def __iter__(self): return iter(constants)
14 def __len__(self): return len(constants)
15 def __getitem__(self, i): return constants[i]
16 def __repr__(self): return 'Enum' + str(names)
17 def __str__(self): return 'enum ' + str(constants)
18
19 class EnumValue(object):
20 __slots__ = ('__value')
21 def __init__(self, value): self.__value = value
22 Value = property(lambda self: self.__value)
23 EnumType = property(lambda self: EnumType)
24 def __hash__(self): return hash(self.__value)
25 def __cmp__(self, other):
26
27
28 assert self.EnumType is other.EnumType, "Only values from the same enum are comparable"
29 return cmp(self.__value, other.__value)
30 def __invert__(self): return constants[maximum - self.__value]
31 def __nonzero__(self): return bool(self.__value)
32 def __repr__(self): return str(names[self.__value])
33
34 maximum = len(names) - 1
35 constants = [None] * len(names)
36 for i, each in enumerate(names):
37 val = EnumValue(i)
38 setattr(EnumClass, each, val)
39 constants[i] = val
40 constants = tuple(constants)
41 EnumType = EnumClass()
42 return EnumType
43
44