Entry
Equivalent of enum
Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 225, Fred L. Drake
"""
Packages: basic_applications.enumeration
"""
"""
> 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]
i
Enjoy!
"""
"""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
# Fred's example, pasted and twiddled by PSST :)
myenum = enumeration(['Foo', 'Bar'], 'myenum')
print myenum.Bar
# myenum.Bar
L = [myenum.Bar, myenum.Foo]
L.sort()
print L
# [myenum.Foo, myenum.Bar]