custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
874 stars 46 forks source link

event_trigger does not work inside closures #434

Closed assumptionsoup closed 1 year ago

assumptionsoup commented 1 year ago
def register_pico_light(pico_id, lights):

    @event_trigger('lutron_caseta_button_event')
    def pico_button_test(**kwargs):
        log.error(f"got EVENT_CALL_SERVICE with {kwargs}")

register_pico_light('<my_device_id>', ['light.desk'])

This doesn't work, but placing pico_button_test outside of the register function does. It would be nice if this was possible.

craigbarratt commented 1 year ago

The issue is that when register_pico_light returns (which is immediately), pico_button_test is no longer referenced and is destroyed. You need to save a reference to the inner function.

See the documentation for trigger closures.