newbie question

Keith Dart kdart at kdart.com
Sun Dec 19 16:43:59 EST 2004


David Wurmfeld wrote:
> I am new to python; any insight on the following would be appreciated, even 
> if it is the admonition to RTFM (as long as you can direct me to a relevant 
> FM)
> 
> Is there a standard approach to enumerated types? I could create a 
> dictionary with a linear set of keys, but isn't this overkill? There is 
> afterall a "True" and "False" enumeration for Boolean.

Not a standard one, but here's what I use:

class Enum(int):
	__slots__ = ("_name")
	def __new__(cls, val, name):
		v = int.__new__(cls, val)
		v._name = str(name)
		return v
	def __str__(self):
		return self._name
	def __repr__(self):
		return "%s(%d, %r)" % (self.__class__.__name__, self, self._name)
	def __cmp__(self, other):
		if isinstance(other, int):
			return int.__cmp__(self, other)
		if type(other) is str:
			return cmp(self._name, other)
		raise ValueError, "Enum comparison with bad type"

class Enums(list):
	def __init__(self, *init):
		for i, val in enumerate(init):
			if issubclass(type(val), list):
				for j, subval in enumerate(val):
					self.append(Enum(i+j, str(subval)))
			elif isinstance(val, Enum):
				self.append(val)
			else:
				self.append(Enum(i, str(val)))
	def __repr__(self):
		return "%s(%s)" % (self.__class__.__name__, list.__repr__(self))



-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Keith Dart <kdart at kdart.com>
    public key: ID: F3D288E4
    =====================================================================



More information about the Python-list mailing list