Cache condition in helpers.Script (#3797)

* Cache condition in helpers.Script

The caching is a simple in-memory, per-instance dictionary.
We use __str__ to format cache keys.

This naive implementation has some disadvantages (e.g., we won't be able
to cache two conditions that contain references to
distinct-but-equivalent object instances and we don't have any control
over the size of the condition cache), but for most simple use-cases the
approach should be good enough.

Resolves #3629

* Fix docstring style
This commit is contained in:
Clemens Wolff 2016-10-10 23:36:38 -07:00 committed by Paulus Schoutsen
parent a2503e4d13
commit 711526e574
2 changed files with 68 additions and 2 deletions

View file

@ -51,6 +51,7 @@ class Script():
in self.sequence)
self._async_unsub_delay_listener = None
self._template_cache = {}
self._config_cache = {}
@property
def is_running(self) -> bool:
@ -153,9 +154,14 @@ class Script():
def _async_check_condition(self, action, variables):
"""Test if condition is matching."""
config_cache_key = frozenset((k, str(v)) for k, v in action.items())
config = self._config_cache.get(config_cache_key)
if not config:
config = condition.async_from_config(action, False)
self._config_cache[config_cache_key] = config
self.last_action = action.get(CONF_ALIAS, action[CONF_CONDITION])
check = condition.async_from_config(action, False)(
self.hass, variables)
check = config(self.hass, variables)
self._log("Test condition {}: {}".format(self.last_action, check))
return check