I have an enum.StrEnum
, for which I want to add attributes to the elements.
For example:
class Fruit(enum.StrEnum):
APPLE = ("Apple", { "color": "red" })
BANANA = ("Banana", { "color": "yellow" })
>>> str(Fruit.APPLE)
"Apple"
>>> Fruit.APPLE.color
"red"
How can I accomplish this? (I'm running Python 3.11.0.)
This question is not a duplicate of this one, which asks about the original enum.Enum
.
CodePudding user response:
The answer is much the same as in the other question (but too long to leave in a comment there):
from enum import StrEnum
class Fruit(StrEnum):
#
def __new__(cls, value, color):
member = str.__new__(cls, value)
member._value_ = value
member.color = color
return member
#
APPLE = "Apple", "red"
BANANA = "Banana", "yellow"
If you really want to use a dict
for the attributes you can, but you run the risk of forgetting an attribute and then one or more of the members will be missing it.