Skip to content

Utilities

rgetattr(obj, attr, *args)

Get recursive attribute.

Examples:

>>> from argparse import Namespace
>>>from pyskroutz.utils import rgetattr
>>> ns_obj = Namespace()
>>> ns_obj.a = Namespace()
>>> ns_obj.a.b = 1
>>> rgetattr(ns_obj, 'a.b')
1

Parameters:

Name Type Description Default
obj

Object.

required
attr str

Attribute name (period separated for nested attributes).

required
*args ()
Source code in pyskroutz/utils.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def rgetattr(obj, attr: str, *args) -> Any:
    """Get recursive attribute.

    Examples:

        >>> from argparse import Namespace
        >>>from pyskroutz.utils import rgetattr
        >>> ns_obj = Namespace()
        >>> ns_obj.a = Namespace()
        >>> ns_obj.a.b = 1
        >>> rgetattr(ns_obj, 'a.b')
        1

    Args:
        obj: Object.
        attr: Attribute name (period separated for nested attributes).
        *args:

    Returns: Attribute value

    """

    def _getattr(obj, attr) -> Any:
        return getattr(obj, attr, *args)

    return functools.reduce(_getattr, [obj] + attr.split("."))

rsetattr(obj, attr, val)

Set attribute recursively.

Examples:

>>> from argparse import Namespace
>>> from pyskroutz.utils import rsetattr
>>> ns_obj = Namespace()
>>> ns_obj.a = Namespace()
>>> rsetattr(ns_obj, 'a.b', 1)
>>> ns_obj.a.b
1

Parameters:

Name Type Description Default
obj object

Object.

required
attr str

Attribute name (period separated for nested attributes).

required
val

Attribute value.

required
Source code in pyskroutz/utils.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def rsetattr(obj: object, attr: str, val) -> Any:
    """Set attribute recursively.

    Examples:

        >>> from argparse import Namespace
        >>> from pyskroutz.utils import rsetattr
        >>> ns_obj = Namespace()
        >>> ns_obj.a = Namespace()
        >>> rsetattr(ns_obj, 'a.b', 1)
        >>> ns_obj.a.b
        1

    Args:
        obj: Object.
        attr: Attribute name (period separated for nested attributes).
        val: Attribute value.
    """
    pre, _, post = attr.rpartition(".")
    return setattr(rgetattr(obj, pre) if pre else obj, post, val)