Skip to content

Instantly share code, notes, and snippets.

@Exchizz
Created April 22, 2021 19:17
Show Gist options
  • Select an option

  • Save Exchizz/0a9f0929ba2d82d328b9fe97b6fd5f72 to your computer and use it in GitHub Desktop.

Select an option

Save Exchizz/0a9f0929ba2d82d328b9fe97b6fd5f72 to your computer and use it in GitHub Desktop.
Python3.8 enum metaclass that supports inheritance (used in django 3.2)
class CustomMetaEnum(type):
def __new__(self, name, bases, namespace):
fields = {}
fields = {key:value for key, value in namespace.items() if isinstance(value, int)}
for base in bases:
fields.update(base._fields)
namespace['_fields'] = fields
return super().__new__(self, name, bases, namespace)
@property
def choices(self):
print("Choices called")
return [(value,key) for key,value in self._fields.items()]
class States(metaclass=CustomMetaEnum):
A = 1
B = 2
C = 3
print("States: ")
print(States.A)
print(States.B)
print(States.choices)
print("MoreStates: ")
class MoreStates(States):
D = 22
pass
print(MoreStates.A)
print(MoreStates.B)
print(MoreStates.C)
print(MoreStates.D)
print(MoreStates.choices)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment