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.

Asked By: Nepo Znat

||

Answers:

If you want the traditional-style “call”, just drop the inheritance from Enum:

class Color:
    GREEN = '#1c5f17'
    BLUE = '#565fcc'
Answered By: iBug

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
Answered By: Mourad Qqch

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
Answered By: Jarrod Burns
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.