Created
July 15, 2022 08:12
-
-
Save Tishka17/d7bcca06a983d027b547053c775dd281 to your computer and use it in GitHub Desktop.
SemiEnum
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
class SemiEnumMeta(type): | |
def __new__(mcs, name, bases, class_dict): | |
class_ = super().__new__(mcs, name, bases, class_dict) | |
class_.__value_mapping = {} | |
for name, value in class_dict.items(): | |
if name.startswith("__"): | |
continue | |
instance = class_(value) | |
setattr(class_, name, instance) | |
class_.__value_mapping[value] = instance | |
return class_ | |
def __call__(self, value): | |
res = self.__value_mapping.get(value) | |
if res: | |
return res | |
return super().__call__(value) | |
class SemiEnum(metaclass=SemiEnumMeta): | |
def __init__(self, value): | |
self.value = value | |
class ErrorType(SemiEnum): | |
x = 1 | |
print(ErrorType(1) is ErrorType.x) | |
print(ErrorType(2).value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment