From 8fd83fbd7dfbd2f8697ad279d56397e0f035250e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mose=20M=C3=BCller?= Date: Tue, 23 Apr 2024 14:21:30 +0200 Subject: [PATCH] updates get_object_attr_from_path to support dictionaries --- src/pydase/utils/helpers.py | 13 +++++-------- tests/utils/test_helpers.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/pydase/utils/helpers.py b/src/pydase/utils/helpers.py index 6124d2e..e2256eb 100644 --- a/src/pydase/utils/helpers.py +++ b/src/pydase/utils/helpers.py @@ -48,15 +48,12 @@ def get_object_attr_from_path(target_obj: Any, path: str) -> Any: """ path_list = path.split(".") if path != "" else [] for part in path_list: + attr, key = parse_keyed_attribute(part) try: - # Try to split the part into attribute and index - attr, index_str = part.split("[", maxsplit=1) - index_str = index_str.replace("]", "") - index = int(index_str) - target_obj = getattr(target_obj, attr)[index] - except ValueError: - # No index, so just get the attribute - target_obj = getattr(target_obj, part) + if key is not None: + target_obj = getattr(target_obj, attr)[key] + else: + target_obj = getattr(target_obj, attr) except AttributeError: # The attribute doesn't exist logger.debug("Attribute % does not exist in the object.", part) diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.py index dfbfb87..f6d47bd 100644 --- a/tests/utils/test_helpers.py +++ b/tests/utils/test_helpers.py @@ -1,7 +1,9 @@ from typing import Any +import pydase import pytest from pydase.utils.helpers import ( + get_object_attr_from_path, is_property_attribute, parse_keyed_attribute, ) @@ -49,6 +51,32 @@ def test_parse_keyed_attributes(attr_name: str, expected: tuple[str, Any]) -> No assert parse_keyed_attribute(attr_name) == expected +def test_get_object_attr_from_path() -> None: + class SubService(pydase.DataService): + name = "SubService" + some_int = 1 + some_float = 1.0 + + class MyService(pydase.DataService): + def __init__(self) -> None: + super().__init__() + self.some_float = 1.0 + self.subservice = SubService() + self.list_attr = [1.0, SubService()] + self.dict_attr = {"foo": SubService()} + + service_instance = MyService() + + for attr_name, obj in [ + ("some_float", service_instance.some_float), + ("subservice", service_instance.subservice), + ("list_attr[0]", service_instance.list_attr[0]), + ("list_attr[1]", service_instance.list_attr[1]), + ("dict_attr['foo']", service_instance.dict_attr["foo"]), + ]: + assert get_object_attr_from_path(service_instance, attr_name) == obj + + # def test_get_nested_dict_by_path() -> None: # obj = {"2.1": "foo", 2.1: "bar"} # serialized_object = {