new enum idiom

Will Ware wware at world.std.com
Sat Jan 6 10:41:58 EST 2001


I stumbled upon a new idiom for enums (at least it's new to me) that
some folks might find helpful. The standard idiom is of course:

(FIRST, SECOND, THIRD) = range(3)

and I would have used this except that I had too many values to count
conveniently. Also I wanted to keep around string versions of the enum
names, for __repr__ purposes. So I hit upon this idiom:

class MidiEvent:

    typeNames = [
        "NOTE_ON", "NOTE_OFF", "POLYPHONIC_KEY_PRESSURE", "CONTROLLER_CHANGE",
        # dozens and dozens more...
        ]

    # build an enum, this is done once when the module is imported
    # locals() gives the namespace for this class, so they become
    # class attributes

    i = 0
    for t in typeNames:
        locals()[t] = i
        i = i + 1

    def __repr__(self):
        # here is where the string versions are used
        r = ("<MidiEvent %s blah blah blah" %
             (self.typeNames[self.type], blah, blah, blah))
        # other info
        return r + ">"
-- 
import string,time,os;print string.join((lambda x:x[:10]+x[8:])(map(
lambda x:string.center("*"*(lambda x:((x<24) ### Seasons Greetings, Will Ware
*(x-3))+3)(x),24),range(1,28, 2))),"\n") ################ wware at world.std.com



More information about the Python-list mailing list