|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from enum import Enum |
| 4 | +from typing import Any, TypeVar |
| 5 | + |
| 6 | +from ..exceptions import CustomValueError, NotFoundEnumValue |
| 7 | +from ..types import FuncExceptT |
| 8 | + |
| 9 | +__all__ = [ |
| 10 | + 'SelfEnum', |
| 11 | + 'CustomEnum', 'CustomIntEnum', 'CustomStrEnum' |
| 12 | +] |
| 13 | + |
| 14 | + |
| 15 | +class CustomEnum(Enum): |
| 16 | + """Base class for custom enums.""" |
| 17 | + |
| 18 | + @classmethod |
| 19 | + def _missing_(cls: type[SelfEnum], value: Any) -> SelfEnum | None: |
| 20 | + return cls.from_param(value) |
| 21 | + |
| 22 | + @classmethod |
| 23 | + def from_param(cls: type[SelfEnum], value: Any, func_except: FuncExceptT | None = None) -> SelfEnum | None: |
| 24 | + """ |
| 25 | + Return the enum value from a parameter. |
| 26 | +
|
| 27 | + :param value: Value to instantiate the enum class. |
| 28 | + :param func_except: Exception function. |
| 29 | +
|
| 30 | + :return: Enum value. |
| 31 | +
|
| 32 | + :raises NotFoundEnumValue: Variable not found in the given enum. |
| 33 | + """ |
| 34 | + |
| 35 | + if value is None: |
| 36 | + return None |
| 37 | + |
| 38 | + if func_except is None: |
| 39 | + func_except = cls.from_param |
| 40 | + |
| 41 | + if isinstance(value, cls): |
| 42 | + return value |
| 43 | + |
| 44 | + if value is cls: |
| 45 | + raise CustomValueError('You must select a member, not pass the enum!', func_except) |
| 46 | + |
| 47 | + try: |
| 48 | + return cls(value) |
| 49 | + except Exception: |
| 50 | + pass |
| 51 | + |
| 52 | + if isinstance(func_except, tuple): |
| 53 | + func_name, var_name = func_except |
| 54 | + else: |
| 55 | + func_name, var_name = func_except, cls |
| 56 | + |
| 57 | + raise NotFoundEnumValue( |
| 58 | + 'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n' |
| 59 | + 'Valid values are: [{readable_enum}].', func_name, |
| 60 | + var_name=var_name, enum_name=cls, value=value, |
| 61 | + readable_enum=iter([f'{x.name} ({x.value})' for x in cls]), |
| 62 | + reason=value |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +class CustomIntEnum(int, CustomEnum): |
| 67 | + """Base class for custom int enums.""" |
| 68 | + |
| 69 | + value: int |
| 70 | + |
| 71 | + |
| 72 | +class CustomStrEnum(str, CustomEnum): |
| 73 | + """Base class for custom str enums.""" |
| 74 | + |
| 75 | + value: str |
| 76 | + |
| 77 | + |
| 78 | +SelfEnum = TypeVar('SelfEnum', bound=CustomEnum) |
0 commit comments