'mappingproxy object' has no attribute

hi,

I have created a template sensor for my WeMo Insight Switch to report the current power in Wh (instead of mWh). It works fine, but now and then the following error appears in the log and I want to know why:

17-03-27 21:11:32 ERROR (MainThread) [homeassistant.components.sensor.template] Could not render template Laundry Wh: UndefinedError: 'mappingproxy object' has no attribute 'current_power_mwh'
- platform: template
  sensors:
    laundry_mwh:
      friendly_name: 'Laundry Wh'
      value_template: >-
          {%- if states.switch.washing_machine %}
              {{ (states.switch.washing_machine.attributes.current_power_mwh / 1000)|round|int }}
          {%  else %}
              0
          {%- endif %}

      unit_of_measurement: 'Wh'

I guess I can add another check to see if the attribute exists, but in all the examples I have seen I have never seen anyone else do this. Is this the way to go?

It would then look like:

- platform: template
  sensors:
    laundry_mwh:
      friendly_name: 'Laundry Wh'
      value_template: >-
          {%- if states.switch.washing_machine and states.switch.washing_machine.attributes.current_power_mwh %}
              {{ (states.switch.washing_machine.attributes.current_power_mwh / 1000)|round|int }}
          {%  else %}
              0
          {%- endif %}

      unit_of_measurement: 'Wh'

Thank you.

3 Likes