Coverage for src/mafw_tools/generic_tools.py: 100%
6 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-04 11:00 +0100
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-04 11:00 +0100
1# Copyright 2025 European Union
2# Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
3# SPDX-License-Identifier: EUPL-1.2
4"""
5Generic utility functions for common operations.
7This module provides utility functions that can be used across different parts
8of the application. Currently, it contains a function for retrieving nested
9attributes from objects using dotted notation.
11.. versionadded:: 1.0.0
13"""
15from typing import Any
18def getattr_nested(obj: Any, attr: str) -> Any:
19 """
20 Retrieve the value of a nested attribute from an object using a dotted path.
22 This function allows accessing nested attributes using dot notation.
23 For example, given an object with a nested structure like ``obj.attr1.attr2``,
24 this function will traverse the path and return the final value.
26 :param obj: The object from which to retrieve the attribute.
27 :type obj: Any
28 :param attr: The dotted path of the attribute to retrieve.
29 :type attr: str
30 :return: The value of the nested attribute.
31 :rtype: Any
32 :raises AttributeError: If any attribute in the path does not exist.
34 :Example:
36 >>> class First:
37 ... def __init__(self, a):
38 ... self.a = a
40 >>> class Second:
41 ... def __init__(self, b):
42 ... self.b = First(b)
44 >>> m = Second(3)
45 >>> getattr_nested(m, 'b.a')
46 3
47 """
48 attrs = attr.split('.')
49 for a in attrs:
50 obj = getattr(obj, a)
51 return obj