Template sensor: even when "available" - an attribute may be not defined

Faced a strange case.
Consider this sensor:

template:
  - sensor:
      - name: testing_transitions
        state: >-
          {% if this.attributes['some_attr'] is defined -%}
            some_state
          {%- else -%}
            attr_not_defined
          {%- endif %}
        attributes:
          some_attr: 123
        availability: >-
          {{ is_state('input_boolean.testing_transitions_availability','on') }}

An availability is controlled by some “input_boolean”.
Here is a timeline (a bottom graph - for that “input_boolean”):

Seems to be OK.

Now the Logbook:

It has enigmatic descriptions for “triggered by” - but this is important:
the state was changed “unavailable” → “attr_not_defined” → “some_state”.

This is also proved by this automation:

trigger:
  - platform: state
    entity_id: sensor.testing_transitions
    to:

action:
  - notify by some way:
          trigger.from_state.state={{trigger.from_state.state}}{{"\n"}}
          trigger.to_state.state={{trigger.to_state.state}}

изображение

Is it normal that an AVAILABLE sensor has an undefined attribute?

AFAIK, this would be considered normal based on load/render order. When the availability resolves to true, the state is rendered, then the attributes are rendered.

1 Like

So, attributes are rendered AFTER a state?
Means: if a state depends on an attribute - this may cause “issues”.
So we should avoid using attributes in a state.

A related issue is here: attributes should not be used to define the same entity’s “availability”.