Scott David Daniels said:
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).