[Python-ideas] constant/enum type in stdlib (original) (raw)

Terry Reedy tjreedy at udel.edu
Wed Jan 30 22:09:31 CET 2013


On 1/30/2013 2:26 AM, Antoine Pitrou wrote:

On Wed, 30 Jan 2013 17:58:37 +1300 Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

Guido van Rossum wrote:

class color(enum): RED = value() WHITE = value() BLUE = value() We could do somewhat better than that: class Color(Enum): RED, WHITE, BLUE = range(3) However, it's still slightly annoying that you have to specify how many values there are in the range() call.

For small enumerations, not much of a problem. Or, if one does not want to take the time to count, allow

RED, WHITE, BLUE, _extras = range(12) # any number >= n

and have a metaclass delete _extras.

Well, how about:

class Color(Enum): values = ('RED', 'WHITE', 'BLUE') ? (replace values with values if you prefer)

I had the same idea, and having never written a metaclass that I can remember, decided to try it.

class EnumMeta(type): def new(cls, name, bases, dic): for i, name in enumerate(dic['_values']): dic[name] = i del dic['_values'] return type.new(cls, name, bases, dic)

class Enum(metaclass=EnumMeta): _values = ()

class Color(Enum): _values = 'RED', 'GREEN', 'BLUE'

print(Color.RED, Color.GREEN, Color.BLUE)

0 1 2

So this syntax is at least feasible -- today.

-- Terry Jan Reedy



More information about the Python-ideas mailing list