Merge pull request #128 from tiqi-group/refactor/remove_unused_attribute_key_from_observers_dict

Refactor: remove unused attribute key from observers dict
This commit is contained in:
Mose Müller 2024-05-21 14:08:48 +02:00 committed by GitHub
commit 2d1d228c78
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 19 additions and 3 deletions

View File

@ -32,6 +32,10 @@ class ObservableObject(ABC):
if attribute in self._observers:
self._observers[attribute].remove(observer)
# remove attribute key from observers dict if list of observers is empty
if not self._observers[attribute]:
del self._observers[attribute]
@abstractmethod
def _remove_observer_if_observable(self, name: str) -> None:
"""Removes the current object as an observer from an observable attribute.

View File

@ -138,7 +138,6 @@ def test_removed_observer_on_class_dict_attr(caplog: pytest.LogCaptureFixture) -
caplog.clear()
assert nested_instance._observers == {
'["nested"]': [],
"nested_attr": [instance],
}
@ -172,7 +171,6 @@ def test_removed_observer_on_instance_dict_attr(
caplog.clear()
assert nested_instance._observers == {
'["nested"]': [],
"nested_attr": [instance],
}
@ -211,6 +209,6 @@ def test_pop(caplog: pytest.LogCaptureFixture) -> None:
instance = MyObservable()
MyObserver(instance)
assert instance.dict_attr.pop("nested") == nested_instance
assert nested_instance._observers == {'["nested"]': []}
assert nested_instance._observers == {}
assert f"'dict_attr' changed to '{instance.dict_attr}'" in caplog.text

View File

@ -81,11 +81,21 @@ def test_removed_observer_on_class_list_attr(caplog: pytest.LogCaptureFixture) -
instance = MyObservable()
MyObserver(instance)
assert nested_instance._observers == {
"[0]": [instance.changed_list_attr],
"nested_attr": [instance],
}
instance.changed_list_attr[0] = "Ciao"
assert "'changed_list_attr[0]' changed to 'Ciao'" in caplog.text
caplog.clear()
assert nested_instance._observers == {
"nested_attr": [instance],
}
instance.nested_attr.name = "Hi"
assert "'nested_attr.name' changed to 'Hi'" in caplog.text
@ -115,6 +125,10 @@ def test_removed_observer_on_instance_list_attr(
assert "'changed_list_attr[0]' changed to 'Ciao'" in caplog.text
caplog.clear()
assert nested_instance._observers == {
"nested_attr": [instance],
}
instance.nested_attr.name = "Hi"
assert "'nested_attr.name' changed to 'Hi'" in caplog.text