Declarative usage of Python's enum.Enum
requires values to be provided, when in the most basic use case for an enum we don't actually care about names and values. We only care about the sentinels themselves. After reading a related Q&A recently, I realised it is possible to use the __prepare__
method of the enum's metaclass to get this kind of declaration:
class Color(Enum):
red
blue
green
And the implementation to make things so dry is actually fairly easy:
from collections import defaultdict
class EnumMeta(type):
@classmethod
def __prepare__(meta, name, bases):
return defaultdict(object)
def __new__(cls, name, bases, classdict):
classdict.default_factory = None
return type.__new__(cls, name, bases, classdict)
class Enum(metaclass=EnumMeta):
pass
In Python 3.6, there was provided enum.auto
to help with that issue of omitting values, but the interface is still strange - you're required to specify the auto()
value for each member, and inherit from a different base which fixes up the __repr__
:
class Color(NoValue):
red = auto()
blue = auto()
green = auto()
Knowing that many man-hours and great care has gone into the implementation chosen for the standard library, there must be some reason why the arguably more Pythonic version of a declarative enum demonstrated earlier doesn't work properly.
My question is, what are the problems and failure modes of the proposed approach, and why was this (or something similar) decided against - with the auto
feature being included in Python 3.6 instead?