Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Enum value without .value attribute

Tags:

python

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.

like image 758
Nepo Znat Avatar asked Feb 18 '26 05:02

Nepo Znat


2 Answers

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

class Color:
    GREEN = '#1c5f17'
    BLUE = '#565fcc'
like image 195
iBug Avatar answered Feb 20 '26 17:02

iBug


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
like image 24
Stephanie Burns Avatar answered Feb 20 '26 18:02

Stephanie Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!