Skip to content

Instantly share code, notes, and snippets.

@EkremDincel
Created October 7, 2020 12:06
Show Gist options
  • Save EkremDincel/b5e0c280a7821e9774225467e278fa97 to your computer and use it in GitHub Desktop.
Save EkremDincel/b5e0c280a7821e9774225467e278fa97 to your computer and use it in GitHub Desktop.
Implementing enumerations in Python using metaclasses.
class EnumMetaDict(dict):
def __init__(self):
self.n = -1
def __getitem__(self, item):
if item.isupper():
self.n += 1
self[item] = self.n
return self.n
return super().__getitem__(item)
class EnumMeta(type):
@classmethod
def __prepare__(meta, name, bases):
return EnumMetaDict()
class Enum(metaclass = EnumMeta):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment