2023-02-01 14:00:27 +00:00
|
|
|
"""Helpers for working with enums."""
|
2024-03-08 15:36:11 +00:00
|
|
|
|
2023-02-12 09:57:36 +00:00
|
|
|
from collections.abc import Callable
|
2023-02-01 14:00:27 +00:00
|
|
|
import contextlib
|
|
|
|
from enum import Enum
|
2024-05-21 07:45:57 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2023-02-12 09:57:36 +00:00
|
|
|
|
|
|
|
# https://github.com/python/mypy/issues/5107
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
2024-05-21 07:45:57 +00:00
|
|
|
def lru_cache[_T: Callable[..., Any]](func: _T) -> _T:
|
2023-02-12 09:57:36 +00:00
|
|
|
"""Stub for lru_cache."""
|
|
|
|
|
|
|
|
else:
|
|
|
|
from functools import lru_cache
|
2023-02-01 14:00:27 +00:00
|
|
|
|
|
|
|
|
2023-02-12 09:57:36 +00:00
|
|
|
@lru_cache
|
2024-05-18 09:43:32 +00:00
|
|
|
def try_parse_enum[_EnumT: Enum](cls: type[_EnumT], value: Any) -> _EnumT | None:
|
2023-02-01 14:00:27 +00:00
|
|
|
"""Try to parse the value into an Enum.
|
|
|
|
|
|
|
|
Return None if parsing fails.
|
|
|
|
"""
|
|
|
|
with contextlib.suppress(ValueError):
|
|
|
|
return cls(value)
|
|
|
|
return None
|