views:

493

answers:

1

So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file.

So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where:

In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones.

In any case where the user supplied yaml does not overlap the default tree, the default tree persists.

Any superflous branches in the tree provided by the user supplied yaml are appended.

I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free.

+4  A: 

You could use PyYAML for parsing the files, and then the following function to merge two trees:

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

Optionally, you could do a deep-copy of the user-tree before calling this function.

MizardX
Why not user.update(default)?
S.Lott
It's default.update(user), since dict.update overwrites existing keys. To know where to recurse deeper into the tree, I would have to iterate over the joined dictionary, which is larger or equal to the largest of user and default.
MizardX