我的程序包含许多配置参数,所以我正在寻找一种方法,将它们都放在一个位置,可以从项目中的每个文件访问.
我想到了一个配置模块,它将充当到包含配置参数的YAML文件的接口.我想要的一个要求是能够使用属性(点)表示法访问配置对象.我找到了AttrDict
库,并编写了以下代码:
import yaml
from attrdict import AttrDict
def get_cfg():
return cfg_node
def dump(out_filepath):
with open(out_filepath, 'w') as file:
yaml.dump(attrdict_to_dict(cfg_node), file)
def load_yaml(filepath):
global cfg_node
with open(filepath, 'r') as file:
cfg_node = dict_to_attrdict(yaml.safe_load(file))
def attrdict_to_dict(myAttrdict):
dictionary = dict(myAttrdict)
for k in myAttrdict:
value = dictionary[k]
if isinstance(value, AttrDict):
dictionary[k] = attrdict_to_dict(value)
return dictionary
def dict_to_attrdict(dictionary):
myAttrdict = AttrDict()
for k in dictionary:
value = dictionary[k]
if isinstance(value, dict):
myAttrdict.__setattr__(k, attrdict_to_dict(value))
return myAttrdict
cfg_node = AttrDict()
cfg_node.b = "value_b"
cfg_node.a = AttrDict()
cfg_node.a.b = AttrDict()
cfg_node.a.c = "nested_c"
cfg_node.a.b.e= "double_nested_e"
问题是这个库不允许嵌套的AttrDict().
print(cfg_node)
>>> {'b': 'value_b', 'a': AttrDict({})}
但是,如果我执行以下操作,嵌套赋值可以工作,但我被迫显式使用嵌套对象,这对我的目的没有用处:
cfg_node = AttrDict()
cfg_node.b = "value_b"
a = AttrDict()
a.c = "nested_value_c"
cfg_node.a = a
print(cfg_node)
>>> {'b': 'value_b', 'a': AttrDict({'c':'nested_value_c'})}