Allow callable coroutines for feature setters (#1272)

This commit is contained in:
Steven B. 2024-11-18 14:53:49 +00:00 committed by GitHub
parent e209d40a6d
commit 0c40939624
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -71,7 +71,7 @@ import logging
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum, auto from enum import Enum, auto
from functools import cached_property from functools import cached_property
from typing import TYPE_CHECKING, Any, Callable from typing import TYPE_CHECKING, Any, Callable, Coroutine
if TYPE_CHECKING: if TYPE_CHECKING:
from .device import Device from .device import Device
@ -136,10 +136,10 @@ class Feature:
name: str name: str
#: Type of the feature #: Type of the feature
type: Feature.Type type: Feature.Type
#: Name of the property that allows accessing the value #: Callable or name of the property that allows accessing the value
attribute_getter: str | Callable | None = None attribute_getter: str | Callable | None = None
#: Name of the method that allows changing the value #: Callable coroutine or name of the method that allows changing the value
attribute_setter: str | None = None attribute_setter: str | Callable[..., Coroutine[Any, Any, Any]] | None = None
#: Container storing the data, this overrides 'device' for getters #: Container storing the data, this overrides 'device' for getters
container: Any = None container: Any = None
#: Icon suggestion #: Icon suggestion
@ -258,11 +258,16 @@ class Feature:
f" - allowed: {self.choices}" f" - allowed: {self.choices}"
) )
if callable(self.attribute_setter):
attribute_setter = self.attribute_setter
else:
container = self.container if self.container is not None else self.device container = self.container if self.container is not None else self.device
if self.type == Feature.Type.Action: attribute_setter = getattr(container, self.attribute_setter)
return await getattr(container, self.attribute_setter)()
return await getattr(container, self.attribute_setter)(value) if self.type == Feature.Type.Action:
return await attribute_setter()
return await attribute_setter(value)
def __repr__(self) -> str: def __repr__(self) -> str:
try: try: