Skip to content

Commit

Permalink
Fix access to embedded status containers (#1682)
Browse files Browse the repository at this point in the history
Also, implement __dir__ to enable autocompletion for attributes of embedded containers.
  • Loading branch information
rytilahti authored Jan 24, 2023
1 parent 2791c39 commit 21aef76
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
13 changes: 13 additions & 0 deletions miio/devicestatus.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import (
Callable,
Dict,
Iterable,
Optional,
Type,
Union,
Expand Down Expand Up @@ -124,11 +125,23 @@ def embed(self, other: "DeviceStatus"):
final_name = f"{other_name}__{name}"
self._settings[final_name] = attr.evolve(setting, property=final_name)

def __dir__(self) -> Iterable[str]:
"""Overridden to include properties from embedded containers."""
return (
list(super().__dir__())
+ list(self._embedded)
+ list(self._sensors)
+ list(self._settings)
)

def __getattr__(self, item):
"""Overridden to lookup properties from embedded containers."""
if item.startswith("__") and item.endswith("__"):
return super().__getattribute__(item)

if item in self._embedded:
return self._embedded[item]

embed, prop = item.split("__", maxsplit=1)
if not embed or not prop:
return super().__getattribute__(item)
Expand Down
7 changes: 7 additions & 0 deletions miio/tests/test_devicestatus.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,10 @@ def sub_sensor(self):
repr(main)
== "<MainStatus main_sensor=main SubStatus=<SubStatus sub_sensor=sub>>"
)

# Test attribute access to the sub status
assert isinstance(main.SubStatus, SubStatus)

# Test that __dir__ is implemented correctly
assert "SubStatus" in dir(main)
assert "SubStatus__sub_sensor" in dir(main)

0 comments on commit 21aef76

Please sign in to comment.