This Python script allows dynamically setting the state and attributes of an entity in Home Assistant. It can be used to modify existing entities or create new ones if allow_create is set to true.
This script requires:
- PythonScriptsPro - A Home Assistant integration that extends the functionality of Python scripts, enabling file operations and better script execution.
- Modify the state of an existing Home Assistant entity.
- Add or update attributes for the specified entity.
- Optionally create a new entity if it does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
entity_id |
string | ✅ True | The entity ID whose state and attributes need to be updated. |
allow_create |
boolean | ❌ False | If true, allows setting a new entity if it doesn't exist. Defaults to false. |
state |
string | ❌ False | The new state to be assigned to the entity. If omitted, the current state is preserved. |
| Other attributes | any | ❌ False | Additional key-value pairs will be added as attributes to the entity. |
action: python_script.exec
data:
entity_id: light.pantry_light
state: 'on'
brightness: 255
file: /config/python_scripts/set_state.pyaction: python_script.exec
data:
entity_id: sensor.hour
state: '14'
file: /config/python_scripts/set_state.pyaction: python_script.exec
data:
entity_id: weather.forecast_dom
temperature: "{{ states('sensor.outside_temperature')}}"
file: /config/python_scripts/set_state.py- Copy the script to the
python_scriptsdirectory in your Home Assistant configuration folder. - Ensure
python_script:is enabled in yourconfiguration.yaml. - Reload Home Assistant or restart the system.