I'm trying to implement a StringAutoEnum class which can set its member values to a lowercase version of the member name without having to call auto() for every single value, as this is verbose and I simply don't like it.
Assuming this base StringAutoEnum class:
import aenum
class StringAutoEnum(aenum.Enum):
def _generate_next_value_(name, start, count, last_values):
return name.lower()
The ideal case would be something like this:
class Animal(StringAutoEnum):
DOG, CAT, SNAKE
Such that the following is True:
Animal.DOG.value == "dog"
Animal.CAT.value == "cat"
Animal.SNAKE.value == "snake"
Obviously, the above class definition is not even valid python code (unless DOG, CAT, and SNAKE have already been defined in advance), so doing it this way is (as far as I'm aware), out of the question.
So, a few alternatives I've considered are the following:
Assignment to multiple variables:
class Animal(StringAutoEnum):
DOG = CAT = SNAKE = auto()
Iterable unpacking:
class Animal(StringAutoEnum):
DOG, CAT, SNAKE = auto()
To reiterate, I do NOT want to have to do this:
class Animal(StringAutoEnum):
DOG, CAT, SNAKE = auto(), auto(), auto()
And I also don't want to have to use the functional API.
The issue with assignment to multiple variables seems to be that auto() is only evaluated once for the first variable name, so all 3 members of the Enum end up with the name 'DOG' and the value 'dog'. I haven't been able to find a workaround for this.
The issue with iterable unpacking is that I can't think of any way of knowing in advance how many variables are on the left side of the assignment operator.
This means that while this will work and will do exactly what I want:
class Auto(aenum.auto):
def __iter__(self):
return iter([Auto() for _ in range(3)])
class Animal(StringAutoEnum):
DOG, CAT, SNAKE = Auto()
This unfortunately will not:
class Animal(StringAutoEnum):
DOG, CAT, SNAKE, EMU = Auto()
And I cannot think of any way of solving it this way for assignment to an arbitrary number of members.
Could anyone think of an alternative way to solve this problem that is clean and concise? Alternatively, could someone propose a workable implementation of assignment to multiple variables/iterable unpacking that works?
Thanks in advance!