From 8460759a315ad5236df149f5c5888eaae713e773 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mose=20M=C3=BCller?= Date: Wed, 2 Aug 2023 12:06:20 +0200 Subject: [PATCH] feat: adding utils.helper --- src/pyDataInterface/utils/__init__.py | 6 +++++- src/pyDataInterface/utils/helpers.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/pyDataInterface/utils/helpers.py diff --git a/src/pyDataInterface/utils/__init__.py b/src/pyDataInterface/utils/__init__.py index c65b108..852eba5 100644 --- a/src/pyDataInterface/utils/__init__.py +++ b/src/pyDataInterface/utils/__init__.py @@ -1,3 +1,7 @@ +from .helpers import get_class_and_instance_attributes from .warnings import warn_if_instance_class_does_not_inherit_from_DataService -__all__ = ["warn_if_instance_class_does_not_inherit_from_DataService"] +__all__ = [ + "warn_if_instance_class_does_not_inherit_from_DataService", + "get_class_and_instance_attributes", +] diff --git a/src/pyDataInterface/utils/helpers.py b/src/pyDataInterface/utils/helpers.py new file mode 100644 index 0000000..4ff956c --- /dev/null +++ b/src/pyDataInterface/utils/helpers.py @@ -0,0 +1,17 @@ +from itertools import chain +from typing import Any + + +def get_class_and_instance_attributes(obj: object) -> dict[str, Any]: + """Dictionary containing all attributes (both instance and class level) of a + given object. + + If an attribute exists at both the instance and class level,the value from the + instance attribute takes precedence. + The __root__ object is removed as this will lead to endless recursion in the for + loops. + """ + + attrs = dict(chain(type(obj).__dict__.items(), obj.__dict__.items())) + attrs.pop("__root__") + return attrs