How to trigger on optional attributes?

I want to trigger an automation based on an attribute that is not always present.
In the following example, the rain attribute might be missing, or is present and numeric.

How can add a check to the condition that it should only trigger if “rain is present” and “rain > 2”?

condition:
  - above: '2'
    condition: numeric_state
    value_template: '{{ state_attr("sensor.my_weather", "rain") }}'

I’m looking for something like the php’s isset()

condition:
  - condition: template
    value_template: '{{ states.sensor.my_weather.attributes.rain is defined and state_attr("sensor.my_weather", "rain") > 2 }}'

If states.sensor.my_weather.attributes.rain is not defined, the test stops there, doesn’t proceed to evaluate the state_attr() function, and the template’s result is false.

Alternate, longer way to do the same thing:

condition:
  - condition: template
    value_template: >
      {% set r = state_attr('sensor.my_weather', 'rain')  %}
      {{ false if r is none or r <= 2 else true }}
1 Like