StrEnum with auto
In many cases you can save yourself some work and use auto().
Since Python 3.11:
Define enum using auto:
from enum import StrEnum, auto
class Color(StrEnum):
RED = auto()
BLUE = auto()
Use the enum:
Color.BLUE == "blue" # True
str(Color.BLUE) # "blue"
By default, auto results in the lower-cased member name as the
value.
It is possible to define a custom enum class to get the original member name:
from enum import StrEnum, auto
class OCaseStrEnum(StrEnum):
"""
StrEnum where enum.auto() returns the original member name, not lower-cased name.
"""
@staticmethod
def _generate_next_value_(name: str, start: int, count: int, last_values: list) -> str:
return name
class Color(OCaseStrEnum):
RED = auto()
BLUE = auto()
Color.BLUE == "BLUE" # True
Before Python 3.11:
Define enum using auto:
from enum import auto
from my_utils import AutoStrEnum
class Color(AutoStrEnum):
RED = auto()
BLUE = auto()
Use the enum:
Color.BLUE == "BLUE" # True
str(Color.BLUE) # "BLUE"
AutoStrEnum definition:
from enum import Enum
class AutoStrEnum(str, Enum):
"""
StrEnum where enum.auto() returns the field name.
See https://docs.python.org/3.9/library/enum.html#using-automatic-values
"""
@staticmethod
def _generate_next_value_(name: str, start: int, count: int, last_values: list) -> str:
return name
# Or if you prefer, return lower-case member (it's StrEnum default behavior since Python 3.11):
# return name.lower()
def __str__(self) -> str:
return self.value # type: ignore
StrEnum can be used as a key:
>>> d = {Color.BLUE: 10, "red": 20}
>>> d["blue"], d[Color.BLUE], d["red"], d[Color.RED]
(10, 10, 20, 20)
repr of StrEnum is different from regular string (see PEP 663):
>>> repr("blue")
"'blue'"
>>> repr(Color.BLUE)
"<Color.BLUE: 'blue'>"
MyEnum.state1.value?str(state)to me...Testround.status? Could you make it of typeMyEnum?'state1' == stateis wrong -- that comparison returnsFalse.