1

When doing a basic Enum in python:

from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 Color.RED.name # "RED" 

the name attribute lets get a string representation of the item which is exactly the strigified name of the attribute: RED => "RED"

Is there a way to update this rule with, for instance, a dict or a factory, so as to have for example:

Color.RED.name # "my color is RED" 

2 Answers 2

3

After digging a bit in the source code of Enum, I have seen that the name attribute is indeed a @DynamicClassAttribute so that doing:

from types import DynamicClassAttribute from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 @DynamicClassAttribute def name(self): name = super(Color, self).name return f"my name is {name}" Color.RED.name # "my name is RED" 

will do the trick

Sign up to request clarification or add additional context in comments.

Comments

0

According to the answer of @clementwalter, a trick to set the Enum name attribute with tuples and a template:

from enum import Enum from types import DynamicClassAttribute class Color(Enum): RED = (1, '[RED]') GREEN = 2 BLUE = 3 def __new__(cls, value, display_name=None): obj = object.__new__(cls) obj._value_ = value obj.display_name = display_name return obj @DynamicClassAttribute def name(self): name = self.display_name or self._name_ # set a name with a tuple name_apply_template = f"my color is {name}" # set all names with a template return name_apply_template print(f"{Color.RED}, {Color.RED.value}, {Color.RED._name_}, {Color.RED.display_name}, {Color.RED.name}") print(f"{Color.GREEN}, {Color.GREEN.value}, {Color.GREEN._name_}, {Color.GREEN.display_name}, {Color.GREEN.name}") # # Results: # Color.RED, 1, RED, [RED], my color is [RED] # Color.GREEN, 2, GREEN, None, my color is GREEN 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.