|
| 1 | +"""Enumeration metaclass.""" |
| 2 | + |
| 3 | +import string |
| 4 | + |
| 5 | +class EnumMetaClass: |
| 6 | + """Metaclass for enumeration. |
| 7 | +
|
| 8 | + To define your own enumeration, do something like |
| 9 | +
|
| 10 | + class Color(Enum): |
| 11 | + red = 1 |
| 12 | + green = 2 |
| 13 | + blue = 3 |
| 14 | +
|
| 15 | + Now, Color.red, Color.green and Color.blue behave totally |
| 16 | + different: they are enumerated values, not integers. |
| 17 | +
|
| 18 | + Enumerations cannot be instantiated; however they can be |
| 19 | + subclassed. |
| 20 | +
|
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, name, bases, dict): |
| 24 | + """Constructor -- create an enumeration. |
| 25 | +
|
| 26 | + Called at the end of the class statement. The arguments are |
| 27 | + the name of the new class, a tuple containing the base |
| 28 | + classes, and a dictionary containing everything that was |
| 29 | + entered in the class' namespace during execution of the class |
| 30 | + statement. In the above example, it would be {'red': 1, |
| 31 | + 'green': 2, 'blue': 3}. |
| 32 | +
|
| 33 | + """ |
| 34 | + for base in bases: |
| 35 | + if base.__class__ is not EnumMetaClass: |
| 36 | + raise TypeError, "Enumeration base class must be enumeration" |
| 37 | + bases = filter(lambda x: x is not Enum, bases) |
| 38 | + self.__name__ = name |
| 39 | + self.__bases__ = bases |
| 40 | + self.__dict = {} |
| 41 | + for key, value in dict.items(): |
| 42 | + self.__dict[key] = EnumInstance(name, key, value) |
| 43 | + |
| 44 | + def __getattr__(self, name): |
| 45 | + """Return an enumeration value. |
| 46 | +
|
| 47 | + For example, Color.red returns the value corresponding to red. |
| 48 | +
|
| 49 | + XXX Perhaps the values should be created in the constructor? |
| 50 | +
|
| 51 | + This looks in the class dictionary and if it is not found |
| 52 | + there asks the base classes. |
| 53 | +
|
| 54 | + The special attribute __members__ returns the list of names |
| 55 | + defined in this class (it does not merge in the names defined |
| 56 | + in base classes). |
| 57 | +
|
| 58 | + """ |
| 59 | + if name == '__members__': |
| 60 | + return self.__dict.keys() |
| 61 | + |
| 62 | + try: |
| 63 | + return self.__dict[name] |
| 64 | + except KeyError: |
| 65 | + for base in self.__bases__: |
| 66 | + try: |
| 67 | + return getattr(base, name) |
| 68 | + except AttributeError: |
| 69 | + continue |
| 70 | + |
| 71 | + raise AttributeError, name |
| 72 | + |
| 73 | + def __repr__(self): |
| 74 | + s = self.__name__ |
| 75 | + if self.__bases__: |
| 76 | + s = s + '(' + string.join(map(lambda x: x.__name__, |
| 77 | + self.__bases__), ", ") + ')' |
| 78 | + if self.__dict: |
| 79 | + list = [] |
| 80 | + for key, value in self.__dict.items(): |
| 81 | + list.append("%s: %s" % (key, int(value))) |
| 82 | + s = "%s: {%s}" % (s, string.join(list, ", ")) |
| 83 | + return s |
| 84 | + |
| 85 | + |
| 86 | +class EnumInstance: |
| 87 | + """Class to represent an enumeration value. |
| 88 | +
|
| 89 | + EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves |
| 90 | + like the integer 12 when compared, but doesn't support arithmetic. |
| 91 | +
|
| 92 | + XXX Should it record the actual enumeration rather than just its |
| 93 | + name? |
| 94 | +
|
| 95 | + """ |
| 96 | + |
| 97 | + def __init__(self, classname, enumname, value): |
| 98 | + self.__classname = classname |
| 99 | + self.__enumname = enumname |
| 100 | + self.__value = value |
| 101 | + |
| 102 | + def __int__(self): |
| 103 | + return self.__value |
| 104 | + |
| 105 | + def __repr__(self): |
| 106 | + return "EnumInstance(%s, %s, %s)" % (`self.__classname`, |
| 107 | + `self.__enumname`, |
| 108 | + `self.__value`) |
| 109 | + |
| 110 | + def __str__(self): |
| 111 | + return "%s.%s" % (self.__classname, self.__enumname) |
| 112 | + |
| 113 | + def __cmp__(self, other): |
| 114 | + return cmp(self.__value, int(other)) |
| 115 | + |
| 116 | + |
| 117 | +# Create the base class for enumerations. |
| 118 | +# It is an empty enumeration. |
| 119 | +Enum = EnumMetaClass("Enum", (), {}) |
| 120 | + |
| 121 | + |
| 122 | +def _test(): |
| 123 | + |
| 124 | + class Color(Enum): |
| 125 | + red = 1 |
| 126 | + green = 2 |
| 127 | + blue = 3 |
| 128 | + |
| 129 | + print Color.red |
| 130 | + print dir(Color) |
| 131 | + |
| 132 | + print Color.red == Color.red |
| 133 | + print Color.red == Color.blue |
| 134 | + print Color.red == 1 |
| 135 | + print Color.red == 2 |
| 136 | + |
| 137 | + class ExtendedColor(Color): |
| 138 | + white = 0 |
| 139 | + orange = 4 |
| 140 | + yellow = 5 |
| 141 | + purple = 6 |
| 142 | + black = 7 |
| 143 | + |
| 144 | + print ExtendedColor.orange |
| 145 | + print ExtendedColor.red |
| 146 | + |
| 147 | + print Color.red == ExtendedColor.red |
| 148 | + |
| 149 | + class OtherColor(Enum): |
| 150 | + white = 4 |
| 151 | + blue = 5 |
| 152 | + |
| 153 | + class MergedColor(Color, OtherColor): |
| 154 | + pass |
| 155 | + |
| 156 | + print MergedColor.red |
| 157 | + print MergedColor.white |
| 158 | + |
| 159 | + print Color |
| 160 | + print ExtendedColor |
| 161 | + print OtherColor |
| 162 | + print MergedColor |
| 163 | + |
| 164 | +if __name__ == '__main__': |
| 165 | + _test() |
0 commit comments