From 5176bb18f499f614e24a119fa360fcde9240cbac Mon Sep 17 00:00:00 2001 From: l0crian1 Date: Sun, 24 Aug 2025 18:27:15 -0400 Subject: T7741: Fixes for 'show interfaces kernel' - Added dict_set_nested helper to set a value in a nested dictionary - Modified get_interface_vrf to accept string or dict as argument - Simplified logic using new helper functions --- python/vyos/utils/dict.py | 34 +++++++++++++++++++++++++++++++++- python/vyos/utils/network.py | 5 ++++- 2 files changed, 37 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/vyos/utils/dict.py b/python/vyos/utils/dict.py index ff21f0677..a43430eed 100644 --- a/python/vyos/utils/dict.py +++ b/python/vyos/utils/dict.py @@ -211,6 +211,39 @@ def dict_set(key_path, value, dict_object): dynamic_dict = dynamic_dict[path_list[i]] dynamic_dict[path_list[len(path_list)-1]] = value +def dict_set_nested(key_path, value, dict_object): + """ + Set value to Python dictionary (dict_object) using a path to the key + delimited by dot ('.'). The key will be added if it does not exist. + Missing keys along the path will be created as nested dictionaries. + + Parameters + ---------- + key_path : str + Dot-delimited path to the key (e.g. "this.is.a.path"). + value : any + The value to set at the final key in the path. + dict_object : dict + Dictionary to modify. Will be updated in place. + + Examples + -------- + d = {} + dict_set_nested("this.is.a.path", 42, d) + # {'this': {'is': {'a': {'path': 42}}}} + + d = {"existing": {"branch": {}}} + dict_set_nested("existing.branch.leaf", "value", d) + # {'existing': {'branch': {'leaf': 'value'}}} + """ + path_list = key_path.split(".") + dynamic_dict = dict_object + for i in range(0, len(path_list) - 1): + if path_list[i] not in dynamic_dict or not isinstance(dynamic_dict[path_list[i]], dict): + dynamic_dict[path_list[i]] = {} + dynamic_dict = dynamic_dict[path_list[i]] + dynamic_dict[path_list[-1]] = value + def dict_delete(key_path, dict_object): """ Delete key in Python dictionary (dict_object) using path to key delimited by dot (.). """ @@ -370,4 +403,3 @@ class FixedDict(dict): if k not in self._allowed: raise ConfigError(f'Option "{k}" has no defined default') super().__setitem__(k, v) - diff --git a/python/vyos/utils/network.py b/python/vyos/utils/network.py index 0e2cc58cf..93f780d8b 100644 --- a/python/vyos/utils/network.py +++ b/python/vyos/utils/network.py @@ -81,7 +81,10 @@ def get_interface_vrf(interface): """ Returns VRF of given interface """ from vyos.utils.dict import dict_search from vyos.utils.network import get_interface_config - tmp = get_interface_config(interface) + if isinstance(interface, str): + tmp = get_interface_config(interface) + elif isinstance(interface, dict): + tmp = interface if dict_search('linkinfo.info_slave_kind', tmp) == 'vrf': return tmp['master'] return 'default' -- cgit v1.2.3