Coverage for src/mafw_tools/generic_tools.py: 100%

1# Copyright 2025 European Union

2# Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)

3# SPDX-License-Identifier: EUPL-1.2

4"""

5 Generic utility functions for common operations.

6

7 This module provides utility functions that can be used across different parts

8 of the application. Currently, it contains a function for retrieving nested

9 attributes from objects using dotted notation.

10

11.. versionadded:: 1.0.0

12

13"""

14

15 from typing import Any

16

17

18 def getattr_nested(obj: Any, attr: str) -> Any:

19 """

20 Retrieve the value of a nested attribute from an object using a dotted path.

21

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.

25

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.

33

34 :Example:

35

36 >>> class First:

37 ... def __init__(self, a):

38 ... self.a = a

39

40 >>> class Second:

41 ... def __init__(self, b):

42 ... self.b = First(b)

43

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