refactor recursive code

This commit is contained in:
Suhas 2021-01-24 19:14:46 -05:00
parent d348dbd55e
commit 9540d34964
2 changed files with 21 additions and 8 deletions

View file

@ -10,7 +10,7 @@ def apply_overrides(overrides: dict, base_config: dict) -> dict:
def recursively_apply(config: dict, nodes: list, override_value) -> dict:
"""Recurse through configuration and apply overrides at the leaf of the config tree
See: https://stackoverflow.com/a/47276490 for algorithm
Credit to iJames on SO: https://stackoverflow.com/a/47276490 for algorithm
Args:
config (dict): loaded configuration from YAML
@ -18,11 +18,18 @@ def recursively_apply(config: dict, nodes: list, override_value) -> dict:
override_value (str): runtime override passed from the command-line
"""
key = nodes[0]
config[key] = (
override_value
if len(nodes) == 1
else recursively_apply(
config[key] if key in config else {}, nodes[1:], override_value
)
)
if len(nodes) == 1:
config[key] = override_value
else:
next_key = nodes[1:]
_recursively_apply(_get_config_node(config, key), next_key, override_value)
return config
def _get_config_node(config: dict, key: str):
if key in config:
pass
else:
config[key] = None
return config[key]