Since one can create an Enum member values of any Data Type: Creating an Enum
Note: Enum member values
Member values can be anything: int, str, etc.. If the exact value is unimportant you may use auto instances and an appropriate value will be chosen for you. Care must be taken if you mix auto with other values.
Sometimes, I see repeating members values of type str
:
from enum import Enum
class Color(Enum):
RED = "RED"
GREEN = "GREEN"
BLUE = "BLUE"
Is it considered as a bad practice to repeat members names with values of type str
?
CodePudding user response:
If the value in your enum is not important, then the type of the value is also not important -- it can be whatever you want.
As far as ease-of-use goes, typing auto()
is probably easier.
CodePudding user response:
I think so. The reason you want to use Enum in the first place is that it's something you couldn't "accidentally" compare to. If you set the member values to "RED"
then I think you would accidentally return true if you compared Color.RED == "RED"
. And this basically defeats the purpose of an Enum in the first place (as in, why not just always use strings RED
, BLUE
, etc.)
If what you want is for your Enum to print a representative string, just override the ___str___
to do so:
def __str__(self):
return self.name```