Question - iif() - How is it evaluated?

This expression works as expected. If button.hvac_filter_reset state is unknown or unavailable the result evaluates to now() with no error.

{% set start = states('button.hvac_filter_reset') %}
{{ iif(start in ['unknown','unavailable'],now(),start|as_datetime) }}

This very similar expression produces this error
UndefinedError: list object has no element 1.

{% set media_player = '' %}
{{ iif(media_player == '','',media_player.split('.')[0] ~ '.mass_' ~ media_player.split('.')[1]) }}

I would expect this to evaluate to ‘’.

I understand the error and resolved it with this.

{% if media_player != '' %} 
  {{ media_player.split('.')[0] ~ '.mass_' ~ media_player.split('.')[1] }}
{% endif %}

What I don’t understand why the iif statement is trying to evaluate the false part of expression. As shown with the first example, this should not happen.

What am I not understanding here?

As it is supposed to, according to the docs which I probably should have read more carefully.

Unlike as_timestamp, as_datetime doesn’t raise an error if supplied an invalid date string, it returns null. I don’t think this was always the case? Anyway, that was the source of my confusion.

1 Like

Not only does it always evaluate the if_true and if_false expressions, it can be inconsistent in how it performs the evaluation.

I reported it earlier this year, in the Core repo, and everyone who replied misunderstood what the Issue was reporting.

They seized on “it’s documented” (if_true and if_false are always evaluated) and promptly closed the Issue. They completely overlooked the main point, and the supplied example, that the evaluation can be inconsistent. When pressed to comment on the inconsistency, they never replied.

1 Like

Very enlightening, thank you. And I kept thinking: Damn, what am I doing wrong?