|
The functional API could stand to be improved a bit: >>> 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'
|