How to handle missing attribute on some entities (binary_sensors) and avoid the UndefinedError

I want to count a few things like the number of open doors and open windows. These are binary sensors and the device_class is ‘door’ for example. So I have been trying to count the number of open doors like this:

{{ states.binary_sensor | selectattr('state', 'eq', 'on') 
|selectattr('attributes.device_class', 'eq', 'door') | list | count }}

When I try this I get the error

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' 
has no attribute 'device_class'

Looking at my binary_sensors there are multiple ones that indeed do not have a device_class. I however cannot figure out how to fix the script above to ignore those sensors that do not even have the attribute. Or perhaps how to I can manually give those sensors a device_class. Looking at it, it’s they are binary sensors added by things like Philips Hue. Not sensors I manually added.

That’s a bug (hopefully fixed with the next update). As a workaround, copy your code into a Markdown Card.

You can exclude entities without device class this way:


{{ states.binary_sensor 
|rejectattr('attributes.device_class', 'defined') 
|selectattr('state', 'eq', 'on')
|list
|count }}

„Custom“ device classes (or other attributes) can be manually added in your customize.yaml.

# Example

cover.tradfri_blind:
  friendly_name: Rollo
  device_class: shade

sensor.hue_bewegungsmelder_flur_battery:
  battery_type: CR2032

2 Likes

Cheers!

I think you ment ‘undefined’?. Updated the door one to the one bellow and the error is now gone and the count seems good.

{{ states.binary_sensor 
|rejectattr('attributes.device_class', 'undefined')
|selectattr('attributes.device_class', 'eq', 'door')
|selectattr('state', 'eq', 'on')
|list
|count }}

Also good to know how I can add device classes if I want to update those. I found out of all the binary sensors its three Hue sensors (media areas) and some Sonos sensors (if the mic is on). Ideally Hue and Sonos would send the right info. But now know how to add it if needed.

2 Likes

Ah, I’ve misunderstood you :+1:

1 Like

No worries. It worked perfectly like this. I had no luck googling it or searching it. So very thankful you posted this solution!

1 Like

Here’s the related issue - which is still not fixed yet: