我正在使用YAML配置文件。下面是在Python中加载我的配置文件的代码:
import os
import yaml
with open('./config.yml') as file:
config = yaml.safe_load(file)
这段代码实际上创建了一个字典。现在的问题是,为了访问值,我需要使用大量的方括号。
YAML:
mysql:
user:
pass: secret
Python:
import os
import yaml
with open('./config.yml') as file:
config = yaml.safe_load(file)
print(config['mysql']['user']['pass']) # <--
我更喜欢像这样使用点表示法(dot notation):
config('mysql.user.pass')
所以,我的想法是利用PyStache的render()接口。
import os
import yaml
with open('./config.yml') as file:
config = yaml.safe_load(file)
import pystache
def get_config_value( yml_path, config ):
return pystache.render('{{' + yml_path + '}}', config)
get_config_value('mysql.user.pass', config)
这是一个“好”的解决方案吗?如果不是,有更好的替代方案吗?
附加问题[已解决]
我决定使用Ilja Everilä的解决方案。但现在我有一个附加问题:如何创建一个包装DotConf的Config类?
下面的代码不起作用,但我希望你能理解我想做什么:
class Config( DotDict ):
def __init__( self ):
with open('./config.yml') as file:
DotDict.__init__(yaml.safe_load(file))
config = Config()
print(config.django.admin.user)
错误:
AttributeError: 'super' object has no attribute '__getattr__'
解决方案
你只需要将self
传递给父类的构造函数即可。
DotDict.__init__(self, yaml.safe_load(file))
更好的解决方案(Ilja Everilä)
super().__init__(yaml.safe_load(file))