equivalent of enum?
Fred L. Drake, Jr.
fdrake at acm.org
Tue Sep 14 10:49:29 EDT 1999
Remco Gerlich writes:
> Is there an equivalent for enumerated types in Python?
I've appended a little code I wrote for this; I like it because the
numeric values are hidden and the printed values are symbolic.
If you store this code as enum.py, use it like this:
>>> import enum
>>> myenum = enum.enumeration(['Foo', 'Bar'], 'myenum')
>>> # You can now "import myenum" elsewhere in the application
... print myenum.Bar
myenum.Bar
>>> L = [myenum.Bar, myenum.Foo]
>>> L.sort()
>>> print L
[myenum.Foo, myenum.Bar]
Enjoy!
-Fred
--
Fred L. Drake, Jr. <fdrake at acm.org>
Corporation for National Research Initiatives
"""Simple enumeration support."""
def enumeration(names, modname):
import new
mod = new.module(modname)
ord = 0
for name in names:
setattr(mod, name, _EnumItem(name, modname, ord))
ord = ord + 1
import sys
sys.modules[modname] = mod
return mod
class _EnumItem:
def __init__(self, name, modname, ord):
self.name = "%s.%s" % (modname, name)
self.modname = modname
self.ord = ord
def __repr__(self):
return self.name
def __cmp__(self, other):
rc = cmp(self.modname, other.modname)
if not rc:
rc = cmp(self.ord, other.ord)
return rc
More information about the Python-list
mailing list