Repository navigation
Conversation
|
Could the trigger arguments be evaluated per instance, with class Thermostat:
def __init__(self, climate, occupancy):
self.climate = climate
self.occupancy = occupancy
@state_trigger(self.climate, f"{self.climate}.*", self.occupancy)
def on_change(self, var_name=None):
log.info(f"{var_name} changed")
living_room = Thermostat("climate.living_room", "binary_sensor.living_room_occupancy")
bedroom = Thermostat("climate.bedroom", "binary_sensor.bedroom_occupancy")With the PR as it is, the arguments can't use
So each instance has to watch every instance's entities and skip the ones that aren't its own, using lists built at module level before the class is defined (no instance exists yet when the class body runs). That moves each object's own data back out of the object. The change looks like it's in two places: If you'd rather keep this PR to its current scope, I can open a separate issue for it. |
|
That sounds pretty useful, I might try it. Not sure if I get to it before next weekend though, and would love to get some maintainer feedback first, if all this is even wanted or implemented in a way that is deemed acceptable. |
|
Works class EntityMonitor:
def __init__(self, entity_id):
self.entity_id = entity_id
@state_trigger(f"{self.entity_id} is not None")
def func(self):
log.info(f"{self.entity_id} changed")
x = EntityMonitor("sensor.solaredge_i1_ac_power")As your example also showed, this is really nice to deal with multiple devices of the same kind. E.g. create a single class for light switches, instantiate it with the respective entity_ids passed, and have the correct object's handler function be triggered on change or something. Very convenient. |
|
Thanks a lot for the effort here — the PR is well put together and comes with tests and docs. As the author of the decorator manager, I reviewed it in detail (including the latest update), and I'd recommend not merging it. Here's why. It doesn't follow Python semantics. In Python, decorators are evaluated once, when the class body runs, and there's no
class Light:
ENTITY = "input_boolean.kitchen"
@state_trigger(f"{ENTITY} == 'on'")
def on_change(self, **kwargs): ...
kitchen = Light() # NameError: name 'ENTITY' is not defined
It adds a lot of complexity to the decorator manager. The DM core is currently small and easy to follow: one manager per function, a fixed set of decorators, a simple lifecycle. This PR spreads method-specific logic across the evaluator, the global context, the manager and the decorators: a class-body flag in I actually tried a very similar architecture while developing the decorator manager, and dropped it in favor of trigger factories, including factories inside classes. They already cover exactly this use case, per-instance arguments like the entity to watch, and they fully match Python semantics: the decorator is evaluated once, when class Light:
def __init__(self, entity):
self.entity = entity
self.trigger = self.make_trigger() # lives as long as the instance keeps it
def make_trigger(self):
@state_trigger(f"{self.entity} == 'on'")
def on_change(value=None):
self.handle(value)
return on_change
def handle(self, value):
log.info(f"{self.entity}: {value}")
kitchen = Light("input_boolean.kitchen")
hall = Light("input_boolean.hall")Instead, a docs PR that adds an example like this to the "Trigger Closures" section might be a good way to make this pattern easier to discover. |
|
Thanks for the feedback, that's what I feared already. I agree, it's not really how python works. I've used those trigger factories in the past too - I just find them fairly cumbersome to use, and it's easy to forget to store the function handle somewhere, and then being surprised it doesn't work - happened to me multiple times. What do you think about this without the |
|
@b3nn0 Thanks for the effort here, and for building the per-instance arguments I asked for. I've switched to the trigger factory pattern dmamelin recommended, with Note to the others on the thread, good documentation examples of this would both help people learning pyscript and help educate AI engines assisting with pyscript on this design pattern. |
|
@b3nn0 Thanks for the detailed reply. Fair point about the strings: the condition is pyscript's own expression language, so As for the implicit Trigger decorators themselves aren't regular Python decorators either: they aren't functions, and pyscript recognizes them by name when a function is defined, so Glad the factories worked out for @jfriend00. I agree that good examples of this pattern in the docs would be useful. In the end, of course, it's @craigbarratt call. |
Trigger decorators on methods with self never really worked. The trigger got registered once when the class was defined, against the class itself, so there was no instance to pass as self when it fired, and every instance ended up sharing one trigger. This PR implements support for that.
The idea is simple: when a trigger decorator lands on a method that takes self, we don't register it right away. We stash the decorator expressions on the class, then register a fresh copy for each instance when it's constructed. Each instance gets its own trigger bound to itself. When an instance is garbage collected, its triggers go away too (a weakref.finalize on the function var handles that), so we don't leave dangling triggers behind for objects that no longer exist.
Methods without self, like a @staticmethod, keep the old class-level behavior, so existing code is unaffected.
While I was in there, I also made self available inside the condition string itself. So this now works:
and only the instance whose self.target matches actually fires. Same thing applies to @state_active and @time_active since they use the same expression code.
There's one subtle bit: evaluating an expression leaves its state vars in the expression context, so the injected self would stick around and keep the instance alive, which breaks the cleanup. I pop it in a finally to avoid that.
Roughly how it fits together: ast_functiondef spots a self method with a trigger and saves the decorators instead of registering them, ast_classdef collects those into pyscript_method_triggers on the class, and call_func calls register_method_triggers right after init to build the per-instance function var and manager. The manager holds a weak ref to the instance and passes it as the first positional arg on dispatch. Positional, not a self= kwarg, because that collides with call_func's own self.
Two things I did not touch on purpose: the legacy dec_trig / trigger_init path, and the fact that the condition watch list still records self.target as a state identifier. That watch is harmless (it never matches), just a little untidy. Cleaning it up is doable but felt out of scope here.
Added tests/test_method_triggers.py covering: per-instance state via self, two independent instances, trigger stops when the instance dies, self-less methods unchanged, and self inside a condition.
Some example: