Skip to content

feat: allow methods as trigger functions, using deferred register on instance creation - #896

Open
b3nn0 wants to merge 5 commits into
custom-components:masterfrom
b3nn0:feat/methods-as-triggers
Open

b3nn0 wants to merge 5 commits into
custom-components:masterfrom
b3nn0:feat/methods-as-triggers

Conversation

@b3nn0

@b3nn0 b3nn0 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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:

@state_trigger("sensor.target == self.target")
def on_match(self, var_name=None, value=None):
    ...

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:

class Foo:

    def __init__(self):
        self.minval = -99999

    @state_trigger("sensor.solaredge_i1_ac_power")
    @time_trigger
    def staticfunc():
        log.info("staticfunc: called")

    @state_trigger("sensor.solaredge_i1_ac_power")
    @time_trigger
    def method(self):
        log.info(f"method: called {sensor.solaredge_i1_ac_power.as_float()}")

    @state_trigger("sensor.solaredge_i1_ac_power.as_float() >= self.minval")
    @time_trigger
    def method_with_self(self):
        log.info("method with self: called")


x = Foo()

@b3nn0 b3nn0 changed the title feat: allow methods as trigger functions, using deferred register on instantiation feat: allow methods as trigger functions, using deferred register on instance creation Nov 17, 2026
@jfriend00

Copy link
Copy Markdown

Could the trigger arguments be evaluated per instance, with self bound to the new instance? The entities we want to trigger on are instance data: each object gets its own entity ids in __init__. For example, one object per thermostat:

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 self:

  • eval_decorators evaluates them in the class body when the method is defined, where there's no self, so this example raises NameError when the class is defined. register_method_triggers evaluates them again for each instance, but without self bound.
  • self in the condition string doesn't help: the watch list comes from the names in the string, so @state_trigger("self.climate") watches an entity named self.climate, as the description notes.

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: register_method_triggers, which already re-evaluates the decorator expressions for each new instance and would need self bound there, and the class-body pass, which would need to skip these arguments.

If you'd rather keep this PR to its current scope, I can open a separate issue for it.

@b3nn0

b3nn0 commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

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.
It's admittedly all a bit "not standard python", since in python, decorators are indeed evaluated at class creation time (and therefore also don't know self).
But as there are a bunch of other non-standard deviations in pyscript already, I wanted to give it a go and see where it leads.

@b3nn0

b3nn0 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@dmamelin

Copy link
Copy Markdown
Contributor

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 self at that point. Here, trigger decorators of a self method are skipped at definition, and their arguments are evaluated later, for every instance, with self injected. That means:

  • @state_trigger(f"{self.entity} == 'on'") isn't valid Python: in plain Python it's a NameError, and linters and IDEs flag self as undefined;
  • class attributes aren't visible to decorator arguments, unlike in Python; this raises NameError when the object is created, and the whole file fails to load:
  class Light:
      ENTITY = "input_boolean.kitchen"

      @state_trigger(f"{ENTITY} == 'on'")
      def on_change(self, **kwargs): ...

  kitchen = Light()  # NameError: name 'ENTITY' is not defined
  • decorators of the same method are evaluated at different times: trigger decorators per instance, other decorators at definition;
  • globals used in decorator arguments are bound when each instance is created, not when the class is defined;
  • an invalid decorator argument isn't reported when the class is defined; instead, the error is logged again for every instance;
  • creating an object becomes an implicit registration, and the trigger's lifetime depends on garbage collection.

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 AstEval, skipping decorators by name in eval_decorators, deferred decorator ASTs on EvalFunc, a separate AstEval per instance to evaluate them, __pyscript_method_triggers__ with MRO lookup on every instantiation, per-instance managers bound through EvalFuncVarClassInst, weak references and finalizers, injecting self into calls, and ExpressionDecorator reaching into the manager's instance and cleaning up AstEval internals. Which decorators get deferred is decided by the legacy TRIG_DECORATORS name list rather than the decorator registry.

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 make_trigger() runs, and self is an ordinary closure variable, so linters and IDEs understand the code just like any other Python. The trigger lives exactly as long as the attribute that holds it:

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.

@b3nn0

b3nn0 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback, that's what I feared already. I agree, it's not really how python works.
But pyscript already has other stuff which is "not how python works". For instance the automatic/implicit async and await.

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 f"{ENTITY}" semenatics of the last commit? So only @state_trigger("sensor.xxx == self.something")?
This would still be valid python, since it's just a string passed into the decorator.
Admittedly, would only give part of the flexibility/only be useful in some cases, and we'd still need the trigger factories for others.

@jfriend00

Copy link
Copy Markdown

@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 self.triggers = self.make_triggers() in __init__. It's running in two of my scripts and working so that's what I'll go with to encapsulate the triggers in the instances that need them.

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.

@dmamelin

Copy link
Copy Markdown
Contributor

@b3nn0 Thanks for the detailed reply. Fair point about the strings: the condition is pyscript's own expression language, so self inside the string doesn't clash with Python the way self in the decorator arguments does.

As for the implicit await: that deviation exists because pyscript runs inside the HA event loop, while users can still write plain sequential code without thinking about async. Otherwise, pyscript tries to stay as close to Python as possible: name resolution, evaluation order and decorator semantics are essentially the same. Here it's the other way around: it changes when and where triggers are registered, for a narrow use case.

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 state_trigger can't be referenced, aliased or overridden like a normal name. That was done on purpose, to stay backward compatible with the legacy implementation. They may become real functions in the future, but I haven't yet found a way to do that while keeping compatibility. It's a good example of why every intentional departure from standard Python is an architectural risk: once it ships, it has to be kept backward compatible, it limits how the subsystem can evolve, and it diverges from what users, linters and IDEs expect.

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.

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.

3 participants