Use Enum value without .value attribute
Question:
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.
Answers:
If you want the traditional-style “call”, just drop the inheritance from Enum
:
class Color:
GREEN = '#1c5f17'
BLUE = '#565fcc'
Since Python 3.8, you can use assignment expressions:
class Color(Enum):
GREEN = (Green := '...')
BLUE = (Blue := '...')
Now, you can keep all the inherited behavior of enums while accessing attributes without .value
like this:
my_color = Color.Green
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
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'
Since Python 3.8, you can use assignment expressions:
class Color(Enum):
GREEN = (Green := '...')
BLUE = (Blue := '...')
Now, you can keep all the inherited behavior of enums while accessing attributes without .value
like this:
my_color = Color.Green
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