Mercurial > hgrepos > Python > libs > ConfigMix
changeset 22:6a91db2c2469
A convenience function to load and merge a list of configuration files with different styles
| author | Franz Glasner <f.glasner@feldmann-mg.com> |
|---|---|
| date | Thu, 10 Mar 2016 15:08:20 +0100 |
| parents | ce290b10dac5 |
| children | c77cb6bc8eeb |
| files | configmix/__init__.py |
| diffstat | 1 files changed, 35 insertions(+), 2 deletions(-) [+] |
line wrap: on
line diff
--- a/configmix/__init__.py Thu Mar 10 13:28:09 2016 +0100 +++ b/configmix/__init__.py Thu Mar 10 15:08:20 2016 +0100 @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -r""" +r"""A library for helping with configuration files. :Author: Franz Glasner :License: BSD License. @@ -15,8 +15,41 @@ import copy +from .config import Configuration -__all__ = [] + +__all__ = ["load", "Configuration"] + + +def load(*files): + """Load the given configuration files, merge them in the given order + and return the resulting `Configuration` dictionary. + + """ + if not files: + return Configuration() + else: + ex = merge(None, _load_cfg_from_file(files[0])) + for f in files: + ex = merge(_load_cfg_from_file(f), ex) + return Configuration(ex) + + +def _load_cfg_from_file(filename): + fnl = filename.lower() + if fnl.endswith(".yml") or fnl.endswith("yaml"): + from . import yaml + with open(filename, "rb") as yf: + return yaml.safe_load(yf) + elif fnl.endswith(".py"): + from . import py + return py.load(filename) + elif fnl.endswith(".ini"): + from . import ini + return ini.load(filename) + else: + raise ValueError("Unknown configuration file type for filename " + "%r" % filename) if 0:
