所以我正在玩弄让自己(当然还有任何关心使用它的人)在 Python 中为 Pygame 制作一个小样板库的想法.我想要一个系统,其中应用程序的设置随 yaml 文件一起提供.
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.
所以我想如果库提供一个默认的 yaml 树并将它与用户提供的树合并它会很有用.出于可用性考虑,我想知道是否有任何人可以预测一个例程:
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:
在树中用户提供的 yaml 与默认值重叠的任何情况下,用户提供的分支都会替换库提供的分支.
In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones.
在用户提供的 yaml 不与默认树重叠的任何情况下,默认树仍然存在.
In any case where the user supplied yaml does not overlap the default tree, the default tree persists.
用户提供的 yaml 提供的树中的任何多余分支都会被附加.
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.
你可以使用 PyYAML 来解析文件,然后使用以下函数合并两棵树:
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
或者,您可以在调用之前对用户树进行 deep-copy这个函数.
Optionally, you could do a deep-copy of the user-tree before calling this function.
这篇关于Python中的Yaml合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!