Is it possible to change an attribute via a script/service?

I have an automation that remembers the level of a light by using an input_number.

I recently discovered that you can easily add custom attributes to any entity (via customize).

It’s easy to return the attribute’s value by using a template, but I can’t figure out a way to set an attribute.

Has anyone figured out a way to do this?

I would say it depends on what you’re trying to do. E.g., you can change/add attributes in the front end via the States page, but that is temporary. As soon as the entity updates itself, those changes will likely be gone.

You say you’ve saved the level of a light. Are you looking to restore the level of the light back to that saved value? If so, then you should use the light.turn_on service and specify brightness.

I guess it would be easier to help if you were a little bit clearer on what you’re trying to do.

FWIW, you might want to check out this python_script I made (which just happens to save and restore switch and light settings :slight_smile:):

I’ve created an attribute of a light called remembered_state. I know I can set it to a remembered brightness with light.turn_on. I’d like to store the light’s brightness value to that attribute.

Looking like that’s not doable by invoking a service. And changing via the states page (or with a rest API call) requires you to set all of the attributes, lest you lose the non-declared attributes.

Ok, I think I get where you’re trying to go now. Save the current level of the light to another attribute of the light’s entity itself. Then, at some later time, maybe use it to restore the light back to that saved level? Something like I did in the python_script, but instead of to another, temporary entity, to the light entity itself, but in a new attribute.

If I got that right, the main issue will be, when the light changes by itself (maybe someone physically/manually changes the physical light), and the HA entity updates itself, that attribute you added (assuming you did it without losing the other attributes) will be gone, since the code knows nothing about it.

I think you’re going to either have to change the python code, or maybe do something like I did - i.e., create a temporary entity to store the information in. Of course, that could be an input_number, like you mentioned earlier. Or, if you do it via the REST API, you can create an entity (that does not have any physical device or component code associated with it, similar to what I did in my python_script.)

Sorry if I misunderstand your ultimate goal.

Ah - looks like my idea won’t work. As you mention - if the light’s state changes, the attribute that I added gets reset to its original state (as defined in customize). So, yeah - I’ll keep on using an input_number as I do in that example linked from my initial post.