import json from copy import deepcopy from typing import Union import confuse if __name__ == '__main__': import dict_utils else: from configs import dict_utils def _set_values(config: Union[confuse.Subview, dict], value): if type(config) in (confuse.OrderedDict, dict): for key in config.keys(): if key in value.keys(): config[key] = _set_values(config[key], value[key]) else: config = value return config class ConfigManager: __configs: confuse.Configuration def __init__(self, file_path: str): self.__file_path: str = file_path self.__configs: confuse.Configuration self.__load_from_file(file_path) @property def configs(self): return deepcopy(self.__configs) def __load_from_file(self, file_path: str): self.__configs = confuse.Configuration('MyApp', __name__) self.__configs.set_file(file_path) def get_lower_dict(self): return dict_utils.to_lower(self.__configs.get()) def update(self, new_dict: dict): new_dict = dict_utils.to_upper(new_dict) self.__configs.set(_set_values(self.__configs.get(), new_dict)) def save(self): with open(self.__file_path, "w") as file_out: file_out.writelines(self.__configs.dump()) def update_n_save(self, new_dict: dict): self.update(new_dict) self.save() def as_json(self): return json.dumps(self.get_lower_dict()) if __name__ == '__main__': conf = ConfigManager('config_test.yaml') print(conf.as_json()) # my_conf = {'process': {'mode': 3}} # conf.update(my_conf) # print(conf.configs)