July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Will Ware
You want to define an
enumeration in the spirit of C’s
enum type.
Python’s introspection facilities let you add a
version of enum, even though Python, as a
language, does not support this construct:
import types, string, pprint, exceptions
class EnumException(exceptions.Exception):
pass
class Enumeration:
def _ _init_ _(self, name, enumList, valuesAreUnique=1):
self._ _doc_ _ = name
lookup = { }
reverseLookup = { }
i = 0
uniqueNames = {}
uniqueValues = {}
for x in enumList:
if type(x) == types.TupleType:
x, i = x
if type(x) != types.StringType:
raise EnumException, "enum name is not a string: " + x
if type(i) != types.IntType:
raise EnumException, "enum value is not an integer: " + i
if uniqueNames.has_key(x):
raise EnumException, "enum name is not unique: " + x
if valuesAreUnique and uniqueValues.has_key(i):
raise EnumException, "enum value is not unique for " + x
uniqueNames[x] = 1
uniqueValues[i] = 1
lookup[x] = i
reverseLookup[i] = x
i = i + 1
self.lookup = lookup
self.reverseLookup = reverseLookup
def _ _getattr_ _(self, attr):
try: return self.lookup[attr]
except KeyError: raise AttributeError
def whatis(self, value):
return self.reverseLookup[value]In C, enum lets you declare several constants, typically with unique values (although you can also explicitly arrange for a value to be duplicated under two different names), without necessarily specifying the actual values (except when you want it to). ...