How to add attributes to a `enum.StrEnum`?

Question:

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.

Asked By: sorbet

||

Answers:

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.

Answered By: Ethan Furman
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.