Skip to content

Commit f2e7472

Browse files
committed
Simplify setting of attributes
Support omitting the value for `state.set('domain.value', some_attr='abc')` and support setting attributes like `domain.value.some_attr = 'abc'`
1 parent b7bb235 commit f2e7472

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

custom_components/pyscript/eval.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1167,9 +1167,15 @@ async def recurse_assign(self, lhs, val):
11671167
return
11681168
if not isinstance(var_name, str):
11691169
raise NotImplementedError(f"unknown lhs type {lhs} (got {var_name}) in assign")
1170-
if var_name.find(".") >= 0:
1170+
dot_count = var_name.count(".")
1171+
if dot_count == 1:
11711172
State.set(var_name, val)
11721173
return
1174+
elif dot_count == 2:
1175+
State.set_attr(var_name, val)
1176+
return
1177+
elif dot_count > 0:
1178+
raise NotImplementedError("variable names may contain at most 2 dots")
11731179
if self.curr_func and var_name in self.curr_func.global_names:
11741180
self.global_sym_table[var_name] = val
11751181
return

custom_components/pyscript/state.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,19 @@ def notify_var_get(cls, var_names, new_vars):
9898
return notify_vars
9999

100100
@classmethod
101-
def set(cls, var_name, value, new_attributes=None, **kwargs):
101+
def set(cls, var_name, value=None, new_attributes=None, **kwargs):
102102
"""Set a state variable and optional attributes in hass."""
103103
if var_name.count(".") != 1:
104104
raise NameError(f"invalid name {var_name} (should be 'domain.entity')")
105-
if new_attributes is None:
105+
106+
state_value = None
107+
if value is None or new_attributes is None:
106108
state_value = cls.hass.states.get(var_name)
109+
110+
if value is None and state_value:
111+
value = state_value.state
112+
113+
if new_attributes is None:
107114
if state_value:
108115
new_attributes = state_value.attributes
109116
else:
@@ -115,6 +122,18 @@ def set(cls, var_name, value, new_attributes=None, **kwargs):
115122
cls.notify_var_last[var_name] = str(value)
116123
cls.hass.states.async_set(var_name, value, new_attributes)
117124

125+
@classmethod
126+
def set_attr(cls, var_attr_name, value):
127+
"""Set a state variable's attribute in hass."""
128+
parts = var_attr_name.split(".")
129+
if len(parts) != 3:
130+
raise NameError(f"invalid name {var_attr_name} (should be 'domain.entity.attr')")
131+
132+
state_var_name = f"{parts[0]}.{parts[1]}"
133+
attr_name = parts[2]
134+
135+
cls.set(state_var_name, **{attr_name: value})
136+
118137
@classmethod
119138
def exist(cls, var_name):
120139
"""Check if a state variable value or attribute exists in hass."""

0 commit comments

Comments
 (0)