enum in Python

Harry George harry.g.george at boeing.com
Tue Sep 9 02:34:18 EDT 2003


Scott David Daniels <Scott.Daniels at Acm.Org> writes:

> David M. Cook wrote:
> 
> > In article <KF67b.33$fd2.25 at newssvr23.news.prodigy.com>, Andrew Chalk wrote:
> >
> >>As a rank Python beginner I've used a dictionary, but presumably there is a
> >>better way.
> > I've seen idioms like FOO, BAR, BAZ = range(3)
> > used.
> > Dave Cook
> 
> For 2.3 or after:
> 
>      class Enumerate(object):
>          def __init__(self, names):
>              for number, name in enumerate(names.split()):
>                  setattr(self, name, number)
> 
> To use:
>      codes = Enumerate('FOO BAR BAZ')
>      codes.BAZ will be 2 and so on.
> 
> 
> if you only have 2.2, precede this with:
> 
>      from __future__ import generators
> 
>      def enumerate(iterable):
>          number = 0
>          for name in iterable:
>              yield number, name
>              number += 1
> 
> 
> 
> 
> codes.BAZ
> 

We have some code which uses fancy cookbooked enumerate patterns but
they seem unnecessarily complex to me.  Even the pattern above is a
runtime build of what should be a static type definition.  Instead, in
any Python version, I use:

class Code:
   unknown=0
   FOO=1
   BAR=2
   BAZ=3

mycode=Code.unknown   #typical initialization

mycode=Code.FOO       #specific value assigned.

You get:
a) type-specific namespace

b) can choose the numbers (e.g., when they are predefined in a data
file format)

c) errors are detected

d) static assignment allows compiler optimizations (don't know if 
any are actually done).

-- 
harry.g.george at boeing.com
6-6M31 Knowledge Management
Phone: (425) 342-5601




More information about the Python-list mailing list