Skip to content

Give .old as None in a @state_trigger with watch, as documented - #946

Open
ALERTua wants to merge 3 commits into
custom-components:masterfrom
ALERTua:fix-watch-old-none
Open

ALERTua wants to merge 3 commits into
custom-components:masterfrom
ALERTua:fix-watch-old-none

Conversation

@ALERTua

@ALERTua ALERTua commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

The docs say that inside a @state_trigger expression, the .old of each state variable that did not cause the evaluation is None. This is true without watch, but with watch the expression raises AttributeError instead, and the trigger does not run. This PR makes the code do what the docs say for .old, so a trigger with watch can read .old of more than one entity, and a trigger with one watched entity can read its .old in the check when the trigger starts. task.wait_until(state_trigger=..., watch=[...]) uses the same trigger code, so it gets the same fix.

Fixes #831.

In #831, dmamelin suggests a larger change: a missing state could give a StateVal with the state unavailable, for each entity. This PR does not take that direction. It gives .old the None that the docs promise and that a trigger without watch already gets, so it does not block that larger change later.

The example that does not work

A function must run when the mains power comes back or when the internet comes back. Two entities, each one with its own "changed from off to on" condition:

@state_trigger(
    "input_boolean.power == 'on' and input_boolean.power.old == 'off'",
    "binary_sensor.internet == 'on' and binary_sensor.internet.old == 'off'",
    watch=["input_boolean.power", "binary_sensor.internet"],
)
def power_or_internet_back(var_name=None):
    log.info(f"{var_name} is back")

When the power comes back while the internet is on, the function does not run, and the log shows this error. These lines come from the log of a real Home Assistant with pyscript fc3b603, without the time stamp. That script compares .old != 'on' in place of .old == 'off', and both forms read the .old of the other entity in the same way. The commits from fc3b603 to 937e05b (3.0.0 and the two commits after it) do not touch this code path:

ERROR (MainThread) [custom_components.pyscript.file.boiler_watchdog]
  File "/config/custom_components/pyscript/decorators/base.py", line 76, in check_expression_vars
    return await self._ast_expression.eval(state_vars)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/pyscript/boiler_watchdog.py", line 3, in file.boiler_watchdog.boiler_watchdog_power_back @state_trigger()
    (binary_sensor.internet == 'on' and binary_sensor.internet.old != 'on')
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'StateVal' object has no attribute 'old'

Each change of one entity while the other entity is on reads the .old of the other entity, so it gives this error. The two expressions are joined with any([...]), so the second one is evaluated even when the first one is true. When the other entity does not exist, the error is NameError: name '<entity>' is not defined instead, and the trigger does not run either.

The case of #831 is the same bug with one watched entity: with state_hold_false (or state_check_now=True), the check when the trigger starts has no .old at all, so binary_sensor.x == 'on' and binary_sensor.x.old == 'off' raises the same error at the start.

The bug is not new: 1.6.4 already gives the watched names in place of the names of the expression, with the same notify_var_get().

Why it happens

  1. A state change gives the trigger two names: the entity and its .old (__init__.py#L444).
  2. With watch, the trigger uses the watch names in place of the names of its expression (decorators/state.py#L198-L203). State.notify_add() keeps these names for the queue of the trigger (state.py#L198).
  3. On each change, State.notify_var_get() adds a value only for these names (state.py#L231-L252). binary_sensor.internet.old is not a watch name, so it gets no value. Without watch, it is one of the names of the expression, and line 244 or line 250 gives it None.
  4. The expression then looks up binary_sensor.internet.old as one name and does not find it. State.exist() is false for it, because old is not an attribute of the entity (eval.py#L1848, state.py#L349-L365).
  5. So ast_attribute() evaluates binary_sensor.internet, gets its StateVal, and calls getattr(val, "old"), which raises AttributeError (eval.py#L1756-L1788). check_expression_vars() logs it and returns False, so the function does not run.
  6. The check when the trigger starts calls State.notify_var_get(self.state_trig_ident, {}), again with only the watch names (decorators/state.py#L302-L306). That is the case of AttributeError: 'StateVal' object has no attribute 'old' #831.

What changes

  • When the trigger has watch and an expression, it collects the X.old and X.old.attr names of its expression.
  • _is_trig_ok() gives these names to State.notify_var_get() before each evaluation. Both places that evaluate the expression go through _is_trig_ok(): the check when the trigger starts and the check of each change. notify_var_get() gives None for such a name, and it skips a name that already has a value, so a .old that the change sets keeps its value. An entity with a real attribute named old keeps that attribute value, as without watch.
  • Only the .old names get a value. notify_var_get() gives None to each dotted name that is not a state (state.py#L250-L251), and the expression reads such a value before it looks for a function of that name (eval.py#L1831-L1842). So a value for each name of the expression would turn state.get into None in an expression with watch, the form that func8 in tests/test_function.py uses.
  • For the same reason, the rest of that docs paragraph stays untrue with watch: an undefined state variable or attribute that the trigger does not watch still raises NameError or AttributeError, as before this PR.
  • Without watch, nothing changes: the trigger collects no names, and _is_trig_ok() evaluates the expression as before.

Evidence

Three new tests in tests/test_function.py:

  • test_state_trigger_watch_other_old_is_none runs the conditions of the example on pyscript.var1 and pyscript.var2. The function writes the entity and its new value, so an extra run (for example when an entity goes off) or a missing run fails the test. The test also reads .old and .old.attr of an entity that no trigger watches.
  • test_state_trigger_watch_old_check_on_start runs the check when the trigger starts with state_check_now=True and with state_hold_false=0, as in AttributeError: 'StateVal' object has no attribute 'old' #831.
  • test_wait_until_watch_other_old_is_none runs task.wait_until() with watch and the .old of an entity that it does not watch.

Without the change in decorators/state.py, all three tests fail with the error from the example. The pyscript fixture finds the logged exceptions:

E       AssertionError: unconsumed pyscript exceptions: [AttributeError("'StateVal' object has no attribute 'old'")]
E       AssertionError: unconsumed pyscript exceptions: [AttributeError("'StateVal' object has no attribute 'old'"), AttributeError("'StateVal' object has no attribute 'old'")]
E       AssertionError: unconsumed pyscript exceptions: [AttributeError("'StateVal' object has no attribute 'old'")]

With the change, all three tests pass.

The example also ran on a real Home Assistant with the first version of this change installed (030f606; a later commit only moves the same code into the watch branch and skips it when there are no names), in a temporary script. Two own entities took the place of input_boolean.power and binary_sensor.internet. The script set both entities to on, then made four changes, one second apart. It had two triggers: A with .old != 'on', and B with .old == 'off', as in the example above. The log showed:

Step A: .old != 'on' B: .old == 'off'
1. The power goes off, the internet is on runs does not run
2. The power comes back, the internet is on runs runs
3. The internet goes off, the power is on runs does not run
4. The internet comes back, the power is on runs runs

No AttributeError was logged. Step 2 is the case that failed before the change. A also runs at steps 1 and 3: the entity that did not change has .old as None, and None != 'on' is true. The same expression does the same without watch, and the docs describe this None. An expression that must catch only a change from off to on compares .old with 'off', as B does.

The checks of CI, run locally on Linux (Ubuntu on WSL2, Python 3.14.8, tests/requirements_test.txt):

  • pytest: 310 passed in 73.53s
  • ruff check and ruff format --check: no findings
  • pylint and mypy on the changed files: no findings

Assisted by Claude Code (Claude Opus 5.5, high effort)

With watch, a @state_trigger expression gets values only for the watched
names. The .old of a variable that did not cause the evaluation is not
among them. pyscript then reads the current state of that variable and
looks for an attribute named old on it, which raises
AttributeError: 'StateVal' object has no attribute 'old', and the trigger
does not run. The check when the trigger starts (state_check_now or
state_hold_false) fails the same way, also with one watched variable.
Without watch, such a .old is None, and the docs say that it is None.

The trigger now collects the X.old and X.old.attr names of its expression
when it is created. Before each evaluation, _is_trig_ok() gives them to
State.notify_var_get(), which already gives None for them. A .old that
the change sets keeps its value. Only the .old names get a value: a value
for each name of the expression would hide functions such as state.get().

Fixes custom-components#831.
The test used .old != 'on', which is true when the .old of the other
entity is None, so the trigger also ran when an entity went off. The
next run wrote the same value to pyscript.done, which fires no state
change, so the test did not see the extra run.

The test now uses .old == 'off', which runs only for a change from off to
on, and writes the new value with the entity name. An extra run or a
missing run now gives a different pyscript.done value and fails the test.
Without watch, the .old names of the expression are already among the
names of the trigger, so the trigger now collects them only when it has
watch, and _is_trig_ok() adds nothing when there are none. The names are
split into parts as the code near it does.

task.wait_until(state_trigger=..., watch=[...]) uses the same trigger
code, and a new test shows that it gives the .old of an entity that it
does not watch as None. The comment and the test docstrings are shorter.
@ALERTua
ALERTua marked this pull request as ready for review December 4, 2026 09:36
@jfriend00

Copy link
Copy Markdown
Contributor

I haven't examined the code in your PR, but if the example in your description is the real problem you're trying to solve, it might be simpler to check what changed in the body of the function, like this, which works on 2.1.1 and 3.0.0:

@state_trigger("input_boolean.power", "binary_sensor.internet")
def power_or_internet_back(var_name=None, value=None, old_value=None):
    if value == "on" and old_value == "off":
        log.info(f"{var_name} is back")

That doesn't address the .old behavior with watch that the PR fixes.

@ALERTua

ALERTua commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

I haven't examined the code in your PR, but if the example in your description is the real problem you're trying to solve, it might be simpler to check what changed in the body of the function, like this, which works on 2.1.1 and 3.0.0:

@state_trigger("input_boolean.power", "binary_sensor.internet")
def power_or_internet_back(var_name=None, value=None, old_value=None):
if value == "on" and old_value == "off":
log.info(f"{var_name} is back")

That doesn't address the .old behavior with watch that the PR fixes.

Thanks! Yes, that works for the example, and it is simpler when the function only needs to filter the changes.

A check in the body cannot replace the expression in two cases:

  • With state_hold_false (or state_check_now), pyscript evaluates the trigger expression itself when the trigger starts, before any change, so there is no old_value yet. That is the case of AttributeError: 'StateVal' object has no attribute 'old' #831, and with watch it fails with the same AttributeError.
  • task.wait_until(state_trigger=..., watch=[...]) has no function body, so the condition can only be in the expression.

So the example in the description is only the shortest form that shows the error.

@jfriend00

Copy link
Copy Markdown
Contributor

Makes sense: state_hold, state_hold_false, state_check_now and task.wait_until() all need the condition in the expression, so .old has to work with watch either way.

@craigbarratt

Copy link
Copy Markdown
Member

Thanks @ALERTua, clear write-up and a nicely narrow fix. The new tests fail on master and pass with this change.

@dmamelin, are you ok with this? It makes .old with watch match the documented None, and doesn't rule out the broader change you suggested in #831 (an unavailable StateVal for missing states) later.

@ALERTua

ALERTua commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking it! I am happy to change anything if @dmamelin sees a problem.

@dmamelin

dmamelin commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Thanks for the PR and the detailed write-up! I'm traveling without my laptop at the moment. I'll take a closer look and reply on Wednesday.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AttributeError: 'StateVal' object has no attribute 'old'

4 participants