Created
May 8, 2018 15:49
-
-
Save ashwch/0d233a4062e3c472dfe81005a7cbebcb to your computer and use it in GitHub Desktop.
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 classproperty(property): | |
| def __get__(self, cls, type): | |
| return self.fget.__get__(None, type)() | |
| class ChoicesEnumMixin(object): | |
| def __new__(cls, value, label=None): | |
| type = cls.get_type() | |
| if type is object: | |
| obj = type.__new__(cls) | |
| else: | |
| obj = type.__new__(cls, value) | |
| obj._value_ = value | |
| obj.label = label if label is not None else six.text_type(value) | |
| return obj | |
| @classproperty | |
| @classmethod | |
| def choices(cls): | |
| return tuple((obj.value, obj.label) for obj in cls) | |
| @classproperty | |
| @classmethod | |
| def values(cls): | |
| return tuple(obj.value for obj in cls) | |
| @classproperty | |
| @classmethod | |
| def labels(cls): | |
| return tuple(obj.label for obj in cls) | |
| def __str__(self): | |
| return six.text_type(self.value) | |
| __repr__ = __str__ | |
| @staticmethod | |
| def get_type(): | |
| raise NotImplementedError | |
| @six.python_2_unicode_compatible | |
| class GenericChoiceEnum(ChoicesEnumMixin, enum.Enum): | |
| @staticmethod | |
| def get_type(): | |
| return object | |
| @six.python_2_unicode_compatible | |
| class ChoiceIntEnum(ChoicesEnumMixin, enum.IntEnum): | |
| @staticmethod | |
| def get_type(): | |
| return int | |
| @six.python_2_unicode_compatible | |
| class ChoiceStringEnum(ChoicesEnumMixin, StringEnum): | |
| @staticmethod | |
| def get_type(): | |
| return six.text_type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment