[Tutor] Python Version of "enum" ?
Lloyd Kvam
pythonTutor at venix.com
Fri Oct 22 00:03:15 CEST 2004
Enum is not built in to Python. Here is my little Enum module. Google
should turn up others.
#enum.py
class Enum(object):
def __init__(self, codes):
for ndx,code in enumerate(codes):
setattr(self, code, ndx)
self.length = len(codes)
if '_codes' not in codes:
self._codes = codes
def __len__(self):
return self.length
typically, usage works like so:
bulb = Enum("OFF,ON".split(','))
bulb.OFF == 0
bulb.ON == 1
It is usually most convenient to keep the Enum instance names fairly
short.
Creating other variations from a list of strings is pretty easy.
enumerate and setattr are the keys to making this work. enumerate
numbers the names in a list. setattr creates object attribute names on
the fly. The main pitfall is that the Enum strings MUST be valid Python
names.
On Thu, 2004-10-21 at 16:47, Gooch, John wrote:
> Is there an equivalent of C++'s 'enum' keyword to set a number of named
> constants ( like so )
> enum {
> OFF,
> ON,
> UNKNOWN
> };
>
> in Python? It makes reading the code a lot simpler, as opposed to having to
> look up what a status of "1" means, it can be replaced with "ON", which is
> much easier to understand.
>
> If not, can you declare named constants another way? Perhaps 'const MONDAY =
> 1', for example.
>
> Thank You,
>
>
> John A. Gooch
> Systems Administrator
> IT - Tools
> EchoStar Satellite L.L.C.
> 9601 S. Meridian Blvd.
> Englewood, CO 80112
> Desk: 720-514-5708
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list