Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions osgar/lib/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Osgar Config Class
"""
import json
import numbers
import sys
from importlib import import_module

Expand Down Expand Up @@ -53,15 +54,21 @@ def config_load(*filenames, application=None):


def merge_dict(dict1, dict2):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The naming is somewhat confusing. It took me some time to realize that dict1 and dict2 and not necessarily dictionaries.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to refactor the code, maybe it is better now.

if not isinstance(dict1, dict) or not isinstance(dict2, dict):
raise MergeConflictError(str((dict1, dict2)))
ret = dict1.copy()
for key in dict2.keys():
if key in dict1:
if dict1[key] != dict2[key]:
ret[key] = merge_dict(dict1[key], dict2[key])
else:
ret[key] = dict2[key]
for key, val2 in dict2.items():
try:
val1 = dict1[key]
if isinstance(val1, dict) and isinstance(val2, dict):
ret[key] = merge_dict(val1, val2)
else:
for t in numbers.Number, str, list, tuple:
if isinstance(val1, t) and isinstance(val2, t):
ret[key] = val2
break
else:
raise MergeConflictError(str((val1, val2)))
except KeyError:
ret[key] = val2
return ret

# vim: expandtab sw=4 ts=4
7 changes: 4 additions & 3 deletions osgar/lib/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ def test_merge_dict(self):
self.assertEqual(merge_dict(dict1, dict2), merge)

self.assertEqual(merge_dict({'A':1}, {'A':1}), {'A':1})

with self.assertRaises(MergeConflictError) as e:
merge_dict({'A':1}, {'A':2})
self.assertEqual(merge_dict({'A':1}, {'A':2}), {'A':2})
self.assertEqual(merge_dict({'A':'a'}, {'A':'b'}), {'A':'b'})
self.assertEqual(merge_dict({'A':[]}, {'A':[1]}), {'A':[1]})
self.assertEqual(merge_dict({'A':()}, {'A':(1,)}), {'A':(1,)})

with self.assertRaises(MergeConflictError) as e:
merge_dict({'A':{'B':1}}, {'A':2})
Expand Down