Skip to content

Commit d31671b

Browse files
authored
Create Commands and States classes to ease access (#17)
1 parent 43368e4 commit d31671b

1 file changed

Lines changed: 37 additions & 3 deletions

File tree

tahoma_api/models.py

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
from __future__ import annotations
2+
13
from enum import Enum
2-
from typing import Any, Dict, List, Optional
4+
from typing import Any, Dict, Iterator, List, Optional
35

46
# pylint: disable=unused-argument, too-many-instance-attributes
57

@@ -52,7 +54,7 @@ def __init__(
5254
self.enabled = enabled
5355
self.label = label
5456
self.controllable_name = controllable_name
55-
self.states = [State(**s) for s in states] if states else None
57+
self.states = States(states) if states else None
5658
self.data_properties = data_properties
5759
self.widget = widget
5860
self.ui_class = ui_class
@@ -73,7 +75,7 @@ def __init__(
7375
qualified_name: str,
7476
**_: Any
7577
) -> None:
76-
self.commands = [CommandDefinition(**cd) for cd in commands]
78+
self.commands = CommandDefinitions(commands)
7779
self.states = [StateDefinition(**sd) for sd in states] if states else None
7880
self.widget_name = widget_name
7981
self.ui_class = ui_class
@@ -110,6 +112,22 @@ def __init__(self, command_name: str, nparams: int, **_: Any) -> None:
110112
self.nparams = nparams
111113

112114

115+
class CommandDefinitions:
116+
def __init__(self, commands: List[Dict[str, Any]]):
117+
self._commands = [CommandDefinition(**command) for command in commands]
118+
119+
def __iter__(self) -> Iterator[CommandDefinition]:
120+
return self._commands.__iter__()
121+
122+
def __contains__(self, name: str) -> bool:
123+
return self.__getitem__(name) is not None
124+
125+
def __getitem__(self, command: str) -> Optional[CommandDefinition]:
126+
return next((cd for cd in self._commands if cd.command_name == command), None)
127+
128+
get = __getitem__
129+
130+
113131
class State:
114132
__slots__ = "name", "value", "type"
115133

@@ -119,6 +137,22 @@ def __init__(self, name: str, value: str, type: str, **_: Any):
119137
self.type = type
120138

121139

140+
class States:
141+
def __init__(self, states: List[Dict[str, Any]]) -> None:
142+
self._states = [State(**state) for state in states]
143+
144+
def __iter__(self) -> Iterator[State]:
145+
return self._states.__iter__()
146+
147+
def __contains__(self, name: str) -> bool:
148+
return self.__getitem__(name) is not None
149+
150+
def __getitem__(self, name: str) -> Optional[State]:
151+
return next((state for state in self._states if state.name == name), None)
152+
153+
get = __getitem__
154+
155+
122156
class Command(dict): # type: ignore
123157
"""Represents an TaHoma Command."""
124158

0 commit comments

Comments
 (0)