Skip to content

Instantly share code, notes, and snippets.

@Tishka17
Created July 15, 2022 08:12
Show Gist options
  • Save Tishka17/d7bcca06a983d027b547053c775dd281 to your computer and use it in GitHub Desktop.
Save Tishka17/d7bcca06a983d027b547053c775dd281 to your computer and use it in GitHub Desktop.
SemiEnum
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