view configmix/__init__.py @ 8:7090c295c940

Two differend tree merge function implementations: not yet finished
author Franz Glasner <hg@dom66.de>
date Wed, 09 Mar 2016 09:05:41 +0100
parents dc058099a4cb
children 6835a5663008
line wrap: on
line source

# -*- coding: utf-8 -*-
r"""

:Author:   Franz Glasner
:License:  BSD License.
           See LICENSE for details.

"""
#
# NOTE: ONLY STANDARDLIB-IMPORTS IN THIS MODULE.
#       ITS JUST FOR BOOTSTRAPPING WITH PYTHON2 and PYTHON3.
#       NO `future`, `six`, ...
#

from __future__ import division, print_function, absolute_import


__version__ = "0.0.dev0"


__all__ = []


#
# From: https://github.com/jet9/python-yconfig/blob/master/yconfig.py
# License: BSD License
#
def dict_merge(a, b):
    """Recursively merges dict's. not just simple a['key'] = b['key'], if
    both a and bhave a key who's value is a dict then dict_merge is called
    on both values and the result stored in the returned dictionary."""

    if not isinstance(b, dict):
        return b
    result = deepcopy(a)
    for k, v in b.iteritems():
        if k in result and isinstance(result[k], dict):
                result[k] = dict_merge(result[k], v)
        else:
            result[k] = deepcopy(v)
    return result


def merge(user, default):
    """A simple (YAML-)tree merge.

    From http://stackoverflow.com/questions/823196/yaml-merge-in-python

    """
    if isinstance(user, dict) and isinstance(default, dict):
        for k,v in default.items():
            if k not in user:
                user[k] = v
            else:
                user[k] = merge(user[k], v)
    return user