Skip to content

Instantly share code, notes, and snippets.

@rtoal
Last active January 15, 2025 21:20
Show Gist options
  • Save rtoal/ad001f89b2ef870d7d611d887a486ea9 to your computer and use it in GitHub Desktop.
Save rtoal/ad001f89b2ef870d7d611d887a486ea9 to your computer and use it in GitHub Desktop.
A lightweight, very convenient function to dynamically create good enums in Python
# 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
@pzelnip
Copy link

pzelnip commented Aug 13, 2020

Why not just use the Enum class in Python? docs.python.org/3/library/enum.html

@rtoal
Copy link
Author

rtoal commented Aug 13, 2020

At the time I wrote this I was not aware that enums were callable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment