1
2
3
4
5
6 """
7 True immutable symbolic enumeration with qualified value access.
8
9 """
10
12
13
14
15 class EnumClass(object):
16 __slots__ = names
17 def __iter__(self):
18 return iter(constants)
19 def __len__(self):
20 return len(constants)
21 def __getitem__(self, i):
22 return constants[i]
23 def __repr__(self):
24 return 'Enum' + str(names)
25 def __str__(self):
26 return 'enum ' + str(constants)
27 def index(self, constant):
28 return list(constants).index(constant)
29
30 class EnumValue(object):
31 __slots__ = ('__value', '__number')
32 def __init__(self, value, number):
33 self.__value = value
34 self.__number = number
35
36 Value = property(lambda self: self.__value)
37 Number = property(lambda self: self.__number)
38 EnumType = property(lambda self: EnumType)
39
40 def __hash__(self):
41 return hash(self.__value)
42 def __cmp__(self, other):
43
44
45
46 if isinstance(self, EnumValue):
47 a = self.__value
48 else:
49 a = None
50
51 if isinstance(other, EnumValue):
52 b = other.__value
53 else:
54 b = None
55
56 return cmp(a, b)
57
58 def __invert__(self):
59 return constants[maximum - self.__value]
60 def __nonzero__(self):
61 return self.__value is not None
62 def __repr__(self):
63 return str(names[self.__value])
64 def __int__(self):
65 return self.__number
66
67 maximum = len(names) - 1
68 constants = [None] * len(names)
69 j = 0
70 for i, each in enumerate(names):
71 val = EnumValue(i, j)
72 setattr(EnumClass, each, val)
73 constants[i] = val
74 j = j + 1
75 constants = tuple(constants)
76 EnumType = EnumClass()
77 return EnumType
78
79
80 if __name__ == '__main__':
81 print '\n*** Enum Demo ***'
82 print '--- Days of week ---'
83 Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')
84 print Days
85 print Days.Mo
86 print Days.Fr
87 print Days.Mo < Days.Fr
88 print list(Days)
89 for each in Days:
90 print 'Day:', each
91 print '--- Yes/No ---'
92 Confirmation = Enum('No', 'Yes')
93 answer = Confirmation.No
94 print 'Your answer is not', ~answer
95 print None == Days.Mo
96 print Days.Mo == None
97