Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Last active August 5, 2024 11:19
Show Gist options
  • Save jonashaag/4e1599349b816198006f2f30190afe69 to your computer and use it in GitHub Desktop.
Save jonashaag/4e1599349b816198006f2f30190afe69 to your computer and use it in GitHub Desktop.
Python Enum with label / verbose name / description
import enum
class EnumWithDisplayName(enum.Enum):
def __new__(cls, value, name=None):
if not hasattr(cls, "_value_to_display_name"):
cls._value_to_display_name = {}
cls._display_name_to_value = {}
if name is not None:
if value in cls._value_to_display_name:
raise NotImplementedError(f"'{cls.__name__}' members must be unique")
if name in cls._display_name_to_value:
raise NotImplementedError(f"'{cls.__name__}' display names must be unique")
cls._value_to_display_name[value] = name
cls._display_name_to_value[name] = value
if not issubclass(cls, value.__class__):
raise TypeError(
"Enum class must be subtype of its value class: " f"'class {cls.__name__}({value.__class__.__name__}, EnumWithDisplayName)'"
)
enum_obj = value.__class__.__new__(cls, value)
enum_obj._value_ = value
return enum_obj
@classmethod
def _missing_(cls, display_name):
if display_name in cls._display_name_to_value:
return cls(cls._display_name_to_value[display_name])
else:
return None
@property
def display_name(self):
return self._value_to_display_name.get(self.value, self.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment