Home Assistant Unofficial Reference 2024.12.1
enum.py
Go to the documentation of this file.
1 """Helpers for working with enums."""
2 
3 from collections.abc import Callable
4 import contextlib
5 from enum import Enum
6 from typing import TYPE_CHECKING, Any
7 
8 # https://github.com/python/mypy/issues/5107
9 if TYPE_CHECKING:
10 
11  def lru_cache[_T: Callable[..., Any]](func: _T) -> _T:
12  """Stub for lru_cache."""
13 
14 else:
15  from functools import lru_cache
16 
17 
18 @lru_cache
19 def try_parse_enum[_EnumT: Enum](cls: type[_EnumT], value: Any) -> _EnumT | None:
20  """Try to parse the value into an Enum.
21 
22  Return None if parsing fails.
23  """
24  with contextlib.suppress(ValueError):
25  return cls(value)
26  return None