Repository navigation
Conversation
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.
|
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 |
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:
So the example in the description is only the shortest form that shows the error. |
|
Makes sense: |
|
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 |
|
Thanks for checking it! I am happy to change anything if @dmamelin sees a problem. |
|
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. |
The docs say that inside a
@state_triggerexpression, the.oldof each state variable that did not cause the evaluation isNone. This is true withoutwatch, but withwatchthe expression raisesAttributeErrorinstead, and the trigger does not run. This PR makes the code do what the docs say for.old, so a trigger withwatchcan read.oldof more than one entity, and a trigger with one watched entity can read its.oldin 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
StateValwith the stateunavailable, for each entity. This PR does not take that direction. It gives.oldtheNonethat the docs promise and that a trigger withoutwatchalready 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:
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.oldof the other entity in the same way. The commits fromfc3b603to937e05b(3.0.0 and the two commits after it) do not touch this code path:Each change of one entity while the other entity is
onreads the.oldof the other entity, so it gives this error. The two expressions are joined withany([...]), so the second one is evaluated even when the first one is true. When the other entity does not exist, the error isNameError: name '<entity>' is not definedinstead, and the trigger does not run either.The case of #831 is the same bug with one watched entity: with
state_hold_false(orstate_check_now=True), the check when the trigger starts has no.oldat all, sobinary_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
.old(__init__.py#L444).watch, the trigger uses thewatchnames 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).State.notify_var_get()adds a value only for these names (state.py#L231-L252).binary_sensor.internet.oldis not awatchname, so it gets no value. Withoutwatch, it is one of the names of the expression, and line 244 or line 250 gives itNone.binary_sensor.internet.oldas one name and does not find it.State.exist()is false for it, becauseoldis not an attribute of the entity (eval.py#L1848,state.py#L349-L365).ast_attribute()evaluatesbinary_sensor.internet, gets itsStateVal, and callsgetattr(val, "old"), which raisesAttributeError(eval.py#L1756-L1788).check_expression_vars()logs it and returnsFalse, so the function does not run.State.notify_var_get(self.state_trig_ident, {}), again with only thewatchnames (decorators/state.py#L302-L306). That is the case of AttributeError: 'StateVal' object has no attribute 'old' #831.What changes
watchand an expression, it collects theX.oldandX.old.attrnames of its expression._is_trig_ok()gives these names toState.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()givesNonefor such a name, and it skips a name that already has a value, so a.oldthat the change sets keeps its value. An entity with a real attribute namedoldkeeps that attribute value, as withoutwatch..oldnames get a value.notify_var_get()givesNoneto 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 turnstate.getintoNonein an expression withwatch, the form thatfunc8intests/test_function.pyuses.watch: an undefined state variable or attribute that the trigger does not watch still raisesNameErrororAttributeError, as before this PR.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_noneruns the conditions of the example onpyscript.var1andpyscript.var2. The function writes the entity and its new value, so an extra run (for example when an entity goesoff) or a missing run fails the test. The test also reads.oldand.old.attrof an entity that no trigger watches.test_state_trigger_watch_old_check_on_startruns the check when the trigger starts withstate_check_now=Trueand withstate_hold_false=0, as in AttributeError: 'StateVal' object has no attribute 'old' #831.test_wait_until_watch_other_old_is_nonerunstask.wait_until()withwatchand the.oldof an entity that it does not watch.Without the change in
decorators/state.py, all three tests fail with the error from the example. Thepyscriptfixture finds the logged exceptions: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 thewatchbranch and skips it when there are no names), in a temporary script. Two own entities took the place ofinput_boolean.powerandbinary_sensor.internet. The script set both entities toon, 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:.old != 'on'.old == 'off'No
AttributeErrorwas 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.oldasNone, andNone != 'on'is true. The same expression does the same withoutwatch, and the docs describe thisNone. An expression that must catch only a change fromofftooncompares.oldwith'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.53sruff checkandruff format --check: no findingspylintandmypyon the changed files: no findingsAssisted by Claude Code (Claude Opus 5.5, high effort)