Created
October 7, 2020 12:06
-
-
Save EkremDincel/b5e0c280a7821e9774225467e278fa97 to your computer and use it in GitHub Desktop.
Implementing enumerations in Python using metaclasses.
This file contains 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
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