enum in Python
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Sep 8 19:17:07 EDT 2003
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
More information about the Python-list
mailing list