How to avoid redundance for entities etc.? #559
-
I'm currently getting into Pyscript and trying to port one of my AppDaemon apps. I haven't tried out the code yet but since I haven't found anything in the documentation related to this, I thought I'd ask what the best way to handle this is. Let's say I have this script @time_trigger("30 10 * * MON,WED,FRI")
def start_cleaning():
vacuum.robot.start()
log.info("The robot vacuum has started cleaning")
@state_trigger("vacuum.robot == 'error'")
def cleaning_has_failed():
log.warning("The robot vacuum has encountered an error while cleaning")
@state_trigger("vacuum.robot.old == 'cleaning' and vacuum.robot == 'returning')
def ... With only these 3 functions I've already used # variables for reusability
robot_entity = "vacuum.robot"
@time_trigger("30 10 * * MON,WED,FRI")
def start_cleaning():
vacuum.start(robot_entity)
log.info("The robot vacuum has started cleaning")
@state_trigger(f"{robot_entity} == 'error'")
def cleaning_has_failed():
log.warning("The robot vacuum has encountered an error while cleaning")
@state_trigger(f"{robot_entity}.old == 'cleaning' and {robot_entity} == 'returning')
def ... This way I can just change the variable at the top and everything else is fine. How do you handle this kinda stuff? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It's a style preference. I prefer your first form since it's clear which entity you are referring to. I don't think the 2nd form helps much since you refer to The 2nd form makes more sense if you have multiple robots and you want to create triggers for each instance. Then all your code would be in a generator function or loop, and using |
Beta Was this translation helpful? Give feedback.
It's a style preference. I prefer your first form since it's clear which entity you are referring to. I don't think the 2nd form helps much since you refer to
robot_entity
an equal number of times, and a reader (like me) unfamiliar with the code would have to take the additional step of looking for the value ofrobot_entity
. It's also slightly confusing since if you later changerobot_entity
to a different value, the previously defined triggers won't change since the decorator's arguments are evaluated once when the function is defined, but the value ofrobot_entity
in the function body will reflect the new value when the function is called. So that could create subtle bugs that would be …