Call a python script from within a data_template

Hi

i’m doing some lengthy IF THEN ELSE , nested, inside jinja. inside a
'service: input_number.set_value
data_template: ’

i get the end value and i’ll assign it to the helper no problem. but during those lengthy nested IF THEN ELSE i discover other things that i’d like to save to other helpers. i’ll discover datetime’s, i’ll discover over values (max, minimums), things that id like to put in other variables/helpers for use in other automations which run later in the day.

sure i could write 5 other automations, each with the exact same code, exporting ONE different desirable variable EACH. but that is duplication of code, which is bad.

i’ve read this python script exists: How to manually set state/value of sensor? - #76 by stuart-i-m-smith

but i cant work out how to call it from within Jinja at the crucial point. the examples show its usage using:‘service: python_script.set_state’ - but that’s not from within a data_template where i am actually discovering the 5 or so values i want to save.

any advice please?

i’ve been searching for a while for an answer but not many people need to do this, it seems.

You can’t call anything from inside templates. I’ve been helping people for 6 (7?) years at this point, and I have rarely seen the need to save a value to a helper. It does happen, I actually have 1 automation that does that. But it’s for the sole purpose of maintaining a date/time that persists through restarts. If that’s not a goal, then I recommend posting your automation as you likely can do what you need without it.

thanks for your reply, you’ve answered my question, it can’t be done from inside a data_template.

i can work out how to do it using 5 automations, but i think for anyone else reading who doesnt want duplicate code across 5 automations to set 5 helpers for later use, it might be a job for a custom python script.

take it out of yaml briefly and do the IF THEN ELSE’s outside and set the helpers from outside, which can be read by other automations later in the day many many times over.

I can guarantee that this is not needed. People tend to only think a certain way when they want to “Set” an entity. 9 times out of 10, a template entity can solve that.

Post your automation. Lets see how it can be reduced into 1 automation with 5 template sensors or a single automation with a single template sensor.