new enum idiom
Jan Dries
jan.dries at dcube-resource.be
Sun Jan 7 16:09:22 EST 2001
Jonathan Polley wrote:
>
> Is is possible to modify the 'enum' function so that I don't have to provide a
> class? I would like to use something like this method to create enumerated types,
> but I don't want to keep generating classes that say:
>
> I would like to just do a:
>
> MIDI_Event = enum("NOTE_ON", "NOTE_OFF", 3, "POLYPHONIC_KEY_PRESSURE",
> "CONTROLLER_CHANGE")
I once wrote a class to simulate enums. Using it, you can write:
colors = enum("GREEN","BLUE","RED","YELLOW")
and you can subsequently refer to the enum constants as:
x = colors.GREEN
If no value is supplied, the first name is assigned 0, the second 1 and
so on. But you can supply values, as in:
colors = enum("GREEN=1","BLUE=0x08","RED","YELLOW")
Anyway, here's the class:
import re
class enum:
def __init__(self,*names):
self.__mnames = {}
value = 0;
for i in names:
pairs = re.split("\s*[=]\s*",i)
if len(pairs) == 2:
value = eval(pairs[1])
self.__mnames[pairs[0]] = value
value += 1
def __getattr__(self,name):
try:
return self.__mnames[name]
except:
raise AttributeError
def __setattr__(self,name,value):
if name == "_enum__mnames":
self.__dict__[name] = value
else:
raise AttributeError
More information about the Python-list
mailing list