Coverage for transformer_lens/utilities/attribute_utils.py: 100%

11 statements  

« prev     ^ index     » next       coverage.py v7.10.1, created at 2026-04-30 01:33 +0000

1"""attribute_utils. 

2 

3This module contains utility functions related to attributes 

4""" 

5 

6from __future__ import annotations 

7 

8 

9def get_nested_attr(obj, attr_str): 

10 """ 

11 Retrieves a nested attribute from an object based on a dot-separated string. 

12 

13 For example, if `attr_str` is "a.b.c", this function will return `obj.a.b.c`. 

14 

15 Args: 

16 obj (Any): The object from which to retrieve the attribute. 

17 attr_str (str): A dot-separated string representing the attribute hierarchy. 

18 

19 Returns: 

20 Any: The value of the nested attribute. 

21 """ 

22 attrs = attr_str.split(".") 

23 for attr in attrs: 

24 obj = getattr(obj, attr) 

25 return obj 

26 

27 

28def set_nested_attr(obj, attr_str, value): 

29 """ 

30 Sets a nested attribute of an object based on a dot-separated string. 

31 

32 For example, if `attr_str` is "a.b.c", this function will set the value of `obj.a.b.c` to `value`. 

33 

34 Args: 

35 obj (Any): The object on which to set the attribute. 

36 attr_str (str): A dot-separated string representing the attribute hierarchy. 

37 value (Any): The value to set for the nested attribute. 

38 """ 

39 attrs = attr_str.split(".") 

40 

41 # Navigate to the deepest object containing the attribute to be set 

42 for attr in attrs[:-1]: 

43 obj = getattr(obj, attr) 

44 

45 # Set the nested attribute's value 

46 setattr(obj, attrs[-1], value)