Coverage for jutil/object.py : 0%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from typing import Tuple, Any
4def _split_obj_attr_path(obj, key: str, exceptions: bool = True) -> Tuple[Any, str]:
5 obj0 = obj
6 key0 = key
7 key_parts = key.split('.')
8 key_path = key_parts[:-1]
9 key_name = key_parts[-1]
10 for next_obj in key_path:
11 if not hasattr(obj, next_obj):
12 if exceptions:
13 raise AttributeError('{} not in {}'.format(key0, obj0))
14 return None, ''
15 obj = getattr(obj, next_obj)
16 return obj, key_name
19def set_obj_attr(obj, key: str, val: Any):
20 """
21 Set object property. Support '.' separate path to sub-objects, for example
22 set_key_value(user, 'profile.address', 'Lapinrinne 1') sets user.profile.address as 'Lapinrinne 1'.
23 :param obj: Object
24 :param key: Attribute name
25 :param val: New attribute value
26 :return: None
27 """
28 obj, key_name = _split_obj_attr_path(obj, key)
29 setattr(obj, key_name, val)
32def get_obj_attr(obj, key: str, default = None, exceptions: bool = True) -> Any:
33 """
34 Get object property. Support '.' separate path to sub-objects, for example
35 get_key_value(user, 'profile.address') gets user.profile.address field value.
36 :param obj: Object
37 :param key: Attribute name
38 :param default: Default return value if exceptions=False
39 :param exceptions: Raise AttributeError or not. Default is True.
40 :return: Attribute value
41 """
42 obj, key_name = _split_obj_attr_path(obj, key, exceptions=exceptions)
43 return getattr(obj, key_name) if obj is not None else default