Skip to content

Instantly share code, notes, and snippets.

Last active Apr 27, 2017
What would you like to do?
include とマージを伴う YAMLベースの configパーサー (試作)
# -*- coding: utf-8 -*-
import yaml
import os
def _yaml_constructor_include(loader, node):
spl = node.value.split(' ')
if len(spl) == 1:
file = spl[0]
keys = None
file, key_list = spl
keys = key_list.split('.')
file_name = os.path.join(os.path.dirname(, file)
with open(file_name) as inputfile:
o = yaml.load(inputfile)
if keys:
for key in keys:
o = o[key]
return o
return o
class YAMLConfigLoader(yaml.Loader):
def initialize_loader(cls):
cls.add_constructor("!include", _yaml_constructor_include)
def load_conf_file(file):
with open(file) as f:
return yaml.load(f, Loader=YAMLConfigLoader)
def load_conf_files(files):
d = dict()
for file in files:
_merge_dict(d, load_conf_file(file))
return d
def _merge_dict(to_dic, from_dic):
for key in from_dic:
if key in to_dic:
to_dic[key] = _merge_object(to_dic[key], from_dic[key])
to_dic[key] = from_dic[key]
return to_dic
def _merge_object(to_obj, from_obj):
if from_obj is None or to_obj is None:
return from_obj
if isinstance(to_obj, dict):
return _merge_dict(to_obj, from_obj)
return from_obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment