Enumerator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class Enumerator(object):
_creation_counter = 0
def __init__(self, name=None, value=None):
if not (value is None or isinstance(value, int)):
raise TypeError('value must be integer')
self._name = name
self._value = value
self._key = None
self._creation_counter = Enumerator._creation_counter
Enumerator._creation_counter += 1
@property
def key(self):
return self._key
@property
def name(self):
return self._name
@property
def value(self):
return self._value
class EnumBase(type):
def __new__(cls, name, bases, attrs):
super_new = super(EnumBase, cls).__new__
parents = [b for b in bases if isinstance(b, EnumBase)]
if not parents:
return super_new(cls, name, bases, attrs)
Enumerator._creation_counter = 0
new_class = super_new(cls, name, bases, attrs)
new_class._enumerators = []
print dir(new_class)
for symbol in dir(new_class):
if symbol.startswith('__'):
continue
obj = getattr(new_class, symbol)
if not isinstance(obj, Enumerator):
continue
obj._key = symbol
if obj._name is None:
obj._name = symbol
new_class._enumerators.insert(obj._creation_counter, obj)
next_val = 0
for obj in new_class._enumerators:
if obj._value is None:
obj._value = next_val
else:
next_val = obj._value
next_val += 1
return new_class
class Enum(object):
__metaclass__ = EnumBase
def __init__(self):
for obj in self._enumerators:
setattr(self, obj.key, obj.value)
################################################################################
class MarkupTypes(Enum):
a = Enumerator()
b = Enumerator()
c = Enumerator()
class SomeTypes(Enum):
d = Enumerator()
e = Enumerator()
f = Enumerator()
if __name__ == '__main__':
typ = MarkupTypes()
print typ.a
print typ.c
print typ.b
# for i in iter(typ):
# print i.name, i.value