Home Assistant Unofficial Reference 2024.12.1
script_variables.py
Go to the documentation of this file.
1 """Script variables."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from homeassistant.core import HomeAssistant, callback
9 
10 from . import template
11 
12 
14  """Class to hold and render script variables."""
15 
16  def __init__(self, variables: dict[str, Any]) -> None:
17  """Initialize script variables."""
18  self.variablesvariables = variables
19  self._has_template_has_template: bool | None = None
20 
21  @callback
23  self,
24  hass: HomeAssistant,
25  run_variables: Mapping[str, Any] | None,
26  *,
27  render_as_defaults: bool = True,
28  limited: bool = False,
29  ) -> dict[str, Any]:
30  """Render script variables.
31 
32  The run variables are used to compute the static variables.
33 
34  If `render_as_defaults` is True, the run variables will not be overridden.
35 
36  """
37  if self._has_template_has_template is None:
38  self._has_template_has_template = template.is_complex(self.variablesvariables)
39 
40  if not self._has_template_has_template:
41  if render_as_defaults:
42  rendered_variables = dict(self.variablesvariables)
43 
44  if run_variables is not None:
45  rendered_variables.update(run_variables)
46  else:
47  rendered_variables = (
48  {} if run_variables is None else dict(run_variables)
49  )
50  rendered_variables.update(self.variablesvariables)
51 
52  return rendered_variables
53 
54  rendered_variables = {} if run_variables is None else dict(run_variables)
55 
56  for key, value in self.variablesvariables.items():
57  # We can skip if we're going to override this key with
58  # run variables anyway
59  if render_as_defaults and key in rendered_variables:
60  continue
61 
62  rendered_variables[key] = template.render_complex(
63  value, rendered_variables, limited
64  )
65 
66  return rendered_variables
67 
68  def as_dict(self) -> dict[str, Any]:
69  """Return dict version of this class."""
70  return self.variablesvariables
dict[str, Any] async_render(self, HomeAssistant hass, Mapping[str, Any]|None run_variables, *bool render_as_defaults=True, bool limited=False)
None __init__(self, dict[str, Any] variables)