-
-
Save datavudeja/e11e5e93dfeca5e0a1353bb3914117b7 to your computer and use it in GitHub Desktop.
Python Enum with label / verbose name / description
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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