Set variable values in scripts (#39915)

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Thomas Lovén
2020-09-11 13:16:25 +02:00
committed by GitHub
parent 8ea8969d80
commit f59e727f16
5 changed files with 129 additions and 9 deletions

View File

@@ -19,21 +19,31 @@ class ScriptVariables:
self,
hass: HomeAssistant,
run_variables: Optional[Mapping[str, Any]],
*,
render_as_defaults: bool = True,
) -> Dict[str, Any]:
"""Render script variables.
The run variables are used to compute the static variables, but afterwards will also
be merged on top of the static variables.
The run variables are used to compute the static variables.
If `render_as_defaults` is True, the run variables will not be overridden.
"""
if self._has_template is None:
self._has_template = template.is_complex(self.variables)
template.attach(hass, self.variables)
if not self._has_template:
rendered_variables = dict(self.variables)
if render_as_defaults:
rendered_variables = dict(self.variables)
if run_variables is not None:
rendered_variables.update(run_variables)
if run_variables is not None:
rendered_variables.update(run_variables)
else:
rendered_variables = (
{} if run_variables is None else dict(run_variables)
)
rendered_variables.update(self.variables)
return rendered_variables
@@ -42,14 +52,11 @@ class ScriptVariables:
for key, value in self.variables.items():
# We can skip if we're going to override this key with
# run variables anyway
if key in rendered_variables:
if render_as_defaults and key in rendered_variables:
continue
rendered_variables[key] = template.render_complex(value, rendered_variables)
if run_variables:
rendered_variables.update(run_variables)
return rendered_variables
def as_dict(self) -> dict: