class Color(Enum): GREEN = '#1c5f17' BLUE = '#565fcc' Is it possible to call Color.GREEN and return '#1c5f17'?
I don't want to call Color.GREEN.value everytime I want to use this.
If you want the traditional-style "call", just drop the inheritance from Enum:
class Color: GREEN = '#1c5f17' BLUE = '#565fcc' IIRC prior to Python 3.11 the official documentation recommended subclassing string:
class Sample(str, Enum): FOO = "foo" BAR = "bar" BAZ = "baz" def __str__(self) -> str: return str.__str__(self) print(Sample.FOO) >>> foo But python 3.11+ users can import StrEnum:
from enum import StrEnum, auto class Sample(StrEnum): FOO = auto() BAR = auto() BAZ = auto() Note: Using auto with StrEnum results in the lower-cased member name as the value.
print(Sample.FOO) >>> foo If you prefer uppercase values:
from enum import StrEnum class Sample(StrEnum): FOO = "FOO" BAR = "BAR" BAZ = "BAZ" print(Sample.FOO) >>> FOO I wanted to Enum some variables to be used as indexes in a big matrix, and I also wanted to remove the .value necessity of the default implementation so I came up with this:
from enum import IntEnum, auto class CustomIntEnum(IntEnum): def __int__(self) -> int: return int.__int__(int(self.value)) class Ex(CustomIntEnum): x = 0 y = auto() print(f"ex.x = {Ex.x} is of type {type(Ex.x)}") print(f"ex.y = {Ex.y} is of type {type(Ex.y)}") array = [5, 6, 7, 8] print(f"but it can be used as index, for example in {array}[ex.x] => {array[Ex.x]}") results in:
0 is of type <enum 'ex'> 1 is of type <enum 'ex'> but it can be used as index, for example in [5, 6, 7, 8][ex.x] => 5 Process finished with exit code 0
Color.GREEN.valueanywhere, you'd haveColor.GREENbeing used at a high level of abstraction, andcolor.valuedown at a lower level.