I prefer the Michael Ford proposed syntax and would gladly port the implementation if possible.
Having to specify either an ordinal number like in BASIC of 1980 or have to specify symbols as strings looks dodgy to me.
class Colors(Enum):
red, green, blue = range(3) red, green, blue = itertools.count()
work too? class Keys(Enum):
space = 1
esc = 2
enter = 3
return = 3 # Alias to "enter".
Also, less magic. >>> Animal = Enum(['ant, 'bee', 'cat', 'dog'])
>>> Animal.ANT
'ant'
I'm not convinced it's useful to pass the class name into the functional API, but I would see value in having an easy API to create enumerated strings. It's easier to see what's going on in other environments (e.g. in a datastore, or in JavaScript) if you pass around string identifiers instead of ints.Here's the class I've been using to do that:
class Constants(object):
def __init__(self, names, enum = False):
self._names = frozenset(names)
if enum:
for (i, name) in enumerate(self._names):
setattr(self, name.upper(), i)
else:
for name in self._names:
setattr(self, name.upper(), name.lower())
self.frozen = True
def keys(self):
return [name.upper() for name in self._names]
def values(self):
return [getattr(self, name.upper()) for name in self._names]
def __setattr__(self, key, value):
if getattr(self, 'frozen', False):
raise Exception("Constants cannot be modified after instantiation")
else:
object.__setattr__(self, key, value)
Example: >>> ImportMethod = Constants(
>>> [
>>> 'email',
>>> 'manual_upload',
>>> 'api',
>>> ]
>>> )
>>>
>>> print(ImportMethod.API)
'api'