Last active
January 15, 2025 21:20
-
-
Save rtoal/ad001f89b2ef870d7d611d887a486ea9 to your computer and use it in GitHub Desktop.
A lightweight, very convenient function to dynamically create good enums in Python
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
# Makes an enum class with instances (class attributes) having uppercase | |
# names while the string representations can be in any case. For example, | |
# Color = enum_class('Color', 'red', 'amber', 'green') returns class Color | |
# with members Color.RED, Color.AMBER, and Color.GREEN. The __str__ instance | |
# methods produce 'red', 'green', and 'blue', respectively. To get the | |
# instance from the string, use, for example, Color.from_string('blue'), | |
# which will return Color.BLUE. | |
def enum_class(classname, *values): | |
cls = type(classname, (), {}) | |
cls._mapping = {} | |
for value in values: | |
attribute = value.upper().replace(' ', '_') | |
instance = cls() | |
setattr(cls, attribute, instance) | |
instance.value = value | |
cls._mapping[value] = instance | |
cls.from_string = lambda value: cls._mapping.get(value) | |
cls.__str__ = lambda self: self.value | |
return cls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not just use the Enum class in Python? docs.python.org/3/library/enum.html