|
| 1 | +""" |
| 2 | +This module contains the ChoiceEnum class, which is a subclass of Enum. |
| 3 | +It adds some useful methods to the Enum class, such as: |
| 4 | + - get_by_value |
| 5 | + - list_as |
| 6 | + - mappings |
| 7 | + - comparison methods etc. |
| 8 | +""" |
| 9 | + |
| 10 | +from abc import ABC, abstractmethod |
| 11 | +from enum import EnumMeta, Enum |
| 12 | + |
| 13 | + |
| 14 | +class IChoice(ABC): |
| 15 | + @classmethod |
| 16 | + @abstractmethod |
| 17 | + def get_by_value(cls, value): |
| 18 | + """Get element by value""" |
| 19 | + |
| 20 | + @classmethod |
| 21 | + @abstractmethod |
| 22 | + def list_as(cls, item_type): |
| 23 | + """List choices as""" |
| 24 | + |
| 25 | + |
| 26 | +class ChoiceEnumMeta(EnumMeta, IChoice, ABC): |
| 27 | + def __contains__(cls, item: int | str) -> bool: |
| 28 | + if isinstance(item, int): |
| 29 | + member_values = [v.value[0] for v in cls.__members__.values()] |
| 30 | + elif isinstance(item, str): |
| 31 | + item = item.lower() |
| 32 | + member_values = [v.value[1].lower() for v in cls.__members__.values()] |
| 33 | + else: |
| 34 | + member_values = cls.__members__.values() |
| 35 | + |
| 36 | + return item in member_values |
| 37 | + |
| 38 | + |
| 39 | +class ChoiceEnum(Enum, metaclass=ChoiceEnumMeta): |
| 40 | + def __str__(self) -> str: |
| 41 | + return self.value[1] |
| 42 | + |
| 43 | + def __int__(self) -> int: |
| 44 | + return self.value[0] |
| 45 | + |
| 46 | + def __eq__(self, other): |
| 47 | + if isinstance(other, str): |
| 48 | + return str(self) == other |
| 49 | + elif isinstance(other, int): |
| 50 | + return int(self) == other |
| 51 | + return self is other |
| 52 | + |
| 53 | + def __hash__(self): |
| 54 | + return hash(f"{self.value[0]}{self.value[1]}") |
| 55 | + |
| 56 | + @classmethod |
| 57 | + def mappings(cls): |
| 58 | + return {elm.value[0]: elm.value[1] for elm in cls} |
| 59 | + |
| 60 | + @classmethod |
| 61 | + def get_by_value(cls, value: str | int): |
| 62 | + value_index = 0 if type(value) == int else 1 |
| 63 | + return next((v for v in cls.__members__.values() if v.value[value_index] == value), None) |
| 64 | + |
| 65 | + @classmethod |
| 66 | + def list_as(cls, item_type) -> list[int | str]: |
| 67 | + if item_type not in [int, str]: |
| 68 | + raise TypeError('Invalid item type') |
| 69 | + return list(map(item_type, cls)) |
0 commit comments