Home Assistant Unofficial Reference 2024.12.1
entity_values.py
Go to the documentation of this file.
1 """A class to hold entity values."""
2 
3 from __future__ import annotations
4 
5 import fnmatch
6 from functools import lru_cache
7 import re
8 from typing import Any
9 
10 from homeassistant.const import MAX_EXPECTED_ENTITY_IDS
11 from homeassistant.core import split_entity_id
12 
13 
15  """Class to store entity id based values.
16 
17  This class is expected to only be used infrequently
18  as it caches all entity ids up to MAX_EXPECTED_ENTITY_IDS.
19 
20  The cache includes `self` so it is important to
21  only use this in places where usage of `EntityValues` is immortal.
22  """
23 
24  def __init__(
25  self,
26  exact: dict[str, dict[str, str]] | None = None,
27  domain: dict[str, dict[str, str]] | None = None,
28  glob: dict[str, dict[str, str]] | None = None,
29  ) -> None:
30  """Initialize an EntityConfigDict."""
31  self._exact_exact = exact
32  self._domain_domain = domain
33 
34  if glob is None:
35  compiled: dict[re.Pattern[str], Any] | None = None
36  else:
37  compiled = {
38  re.compile(fnmatch.translate(key)): value for key, value in glob.items()
39  }
40 
41  self._glob_glob = compiled
42 
43  @lru_cache(maxsize=MAX_EXPECTED_ENTITY_IDS)
44  def get(self, entity_id: str) -> dict[str, str]:
45  """Get config for an entity id."""
46  domain, _ = split_entity_id(entity_id)
47  result: dict[str, str] = {}
48 
49  if self._domain_domain is not None and domain in self._domain_domain:
50  result.update(self._domain_domain[domain])
51 
52  if self._glob_glob is not None:
53  for pattern, values in self._glob_glob.items():
54  if pattern.match(entity_id):
55  result.update(values)
56 
57  if self._exact_exact is not None and entity_id in self._exact_exact:
58  result.update(self._exact_exact[entity_id])
59 
60  return result
dict[str, str] get(self, str entity_id)
None __init__(self, dict[str, dict[str, str]]|None exact=None, dict[str, dict[str, str]]|None domain=None, dict[str, dict[str, str]]|None glob=None)
tuple[str, str] split_entity_id(str entity_id)
Definition: core.py:214