Skip to content

Instantly share code, notes, and snippets.

@kokumura
Last active April 27, 2017 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kokumura/c6693284441200caf420416cb5a5b38f to your computer and use it in GitHub Desktop.
Save kokumura/c6693284441200caf420416cb5a5b38f to your computer and use it in GitHub Desktop.
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
else:
file, key_list = spl
keys = key_list.split('.')
file_name = os.path.join(os.path.dirname(loader.name), file)
with open(file_name) as inputfile:
o = yaml.load(inputfile)
if keys:
for key in keys:
o = o[key]
return o
else:
return o
class YAMLConfigLoader(yaml.Loader):
@classmethod
def initialize_loader(cls):
cls.add_constructor("!include", _yaml_constructor_include)
YAMLConfigLoader.initialize_loader()
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])
else:
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)
else:
return from_obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment