Go to the documentation of this file.00001
00002
00003 import os
00004 import collections
00005
00006 def make_dir_list(path):
00007 """ Create list from path where each directory is one list entry """
00008 front,back = os.path.split(path)
00009 if not back and not front:
00010 return []
00011 if not back:
00012 return make_dir_list(front)
00013 if not front:
00014 return [ back ]
00015 frontL = make_dir_list(front)
00016 backL = make_dir_list(back)
00017 if not frontL:
00018 return backL
00019 if not backL:
00020 return frontL
00021 theList = []
00022 theList.extend(frontL)
00023 theList.extend(backL)
00024 return theList
00025
00026 def behaves_like_dict(object):
00027 """Check if object is dict-like"""
00028 return isinstance(object, collections.Mapping)
00029
00030
00031 def merge(a, b):
00032 """Merge two deep dicts non-destructively
00033
00034 Uses a stack to avoid maximum recursion depth exceptions
00035
00036 >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
00037 >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
00038 >>> c = merge(a, b)
00039 >>> from pprint import pprint; pprint(c)
00040 {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
00041 """
00042 assert behaves_like_dict(a), behaves_like_dict(b)
00043 dst = a.copy()
00044
00045 stack = [(dst, b)]
00046 while stack:
00047 current_dst, current_src = stack.pop()
00048 for key in current_src:
00049 if key not in current_dst:
00050 current_dst[key] = current_src[key]
00051 else:
00052 if behaves_like_dict(current_src[key]) and behaves_like_dict(current_dst[key]) :
00053 stack.append((current_dst[key], current_src[key]))
00054 else:
00055 current_dst[key] = current_src[key]
00056 return dst
00057