| 1 |
"""Enum utilities.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import Any, Self, cast |
| 6 |
|
| 7 |
from asusrouter.tools.converters import clean_string, safe_int |
| 8 |
|
| 9 |
|
| 10 |
class FromIntMixin: |
| 11 |
"""Mixin providing a `from_value` classmethod for int-based enums. |
| 12 |
|
| 13 |
Any enum inheriting from this mixin have to define an `UNKNOWN` member. |
| 14 |
""" |
| 15 |
|
| 16 |
@classmethod |
| 17 |
def from_value(cls, value: Any) -> Self: |
| 18 |
"""Resolve an enum member.""" |
| 19 |
|
| 20 |
# If already an enum member, return it |
| 21 |
if isinstance(value, cls): |
| 22 |
return value |
| 23 |
|
| 24 |
# Try integer conversion first |
| 25 |
vint = safe_int(value) |
| 26 |
if vint is not None: |
| 27 |
try: |
| 28 |
return cls(vint) # type: ignore[call-arg] |
| 29 |
except ValueError: |
| 30 |
pass |
| 31 |
|
| 32 |
# Try key names |
| 33 |
vstr = clean_string(value) |
| 34 |
if isinstance(vstr, str): |
| 35 |
member = getattr(cls, vstr.upper(), None) |
| 36 |
if member is not None: |
| 37 |
return cast(Self, member) |
| 38 |
|
| 39 |
# Fallback to UNKNOWN member if defined on the enum class |
| 40 |
unknown = getattr(cls, "UNKNOWN", None) |
| 41 |
if unknown is not None: |
| 42 |
return cast(Self, unknown) |
| 43 |
|
| 44 |
raise ValueError( |
| 45 |
f"{cls.__name__}.from_value: cannot resolve {value!r} " |
| 46 |
"and no `UNKNOWN` member is defined" |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
class FromStrMixin: |
| 51 |
"""Mixin providing a `from_value` classmethod for string-based enums. |
| 52 |
|
| 53 |
Any enum inheriting from this mixin have to define an `UNKNOWN` member. |
| 54 |
""" |
| 55 |
|
| 56 |
@classmethod |
| 57 |
def from_value(cls, value: Any) -> Self: |
| 58 |
"""Resolve an enum member from a string value.""" |
| 59 |
|
| 60 |
# If already an enum member, return it |
| 61 |
if isinstance(value, cls): |
| 62 |
return value |
| 63 |
|
| 64 |
vstr = clean_string(value) |
| 65 |
if isinstance(vstr, str): |
| 66 |
# Check whether this is a value |
| 67 |
value_map = getattr(cls, "_value2member_map_", {}) |
| 68 |
member = value_map.get(vstr) |
| 69 |
if member is not None: |
| 70 |
return cast(Self, member) |
| 71 |
|
| 72 |
# Check if a key exists |
| 73 |
member = getattr(cls, vstr.upper(), None) |
| 74 |
if member is not None: |
| 75 |
return cast(Self, member) |
| 76 |
|
| 77 |
# Fallback to UNKNOWN member if defined on the enum class |
| 78 |
unknown = getattr(cls, "UNKNOWN", None) |
| 79 |
if unknown is not None: |
| 80 |
return cast(Self, unknown) |
| 81 |
|
| 82 |
raise ValueError( |
| 83 |
f"{cls.__name__}.from_value: cannot resolve {value!r} " |
| 84 |
"and no `UNKNOWN` member is defined" |
| 85 |
) |