Skip to content

Commit

Permalink
[utils] Implemented identifiers as parameters in utils.merge_list
Browse files Browse the repository at this point in the history
This will allow each backend to supply its own list
of supported identifiers for the merge_list function.
  • Loading branch information
nemesifier committed Jan 24, 2017
1 parent 321bab0 commit 6f712d1
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions netjsonconfig/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ def merge_config(template, config):
return result


def merge_list(list1, list2):
def merge_list(list1, list2, identifiers=['name', 'id']):
"""
Merges ``list2`` on top of ``list1``.
If both lists contain dictionaries which have keys like
``name`` or ``id`` of equal values, those dicts are merged
(dicts in ``list2`` will override dicts in ``list1``).
If both lists contain dictionaries which have keys specified
in ``identifiers`` which have equal values, those dicts will
be merged (dicts in ``list2`` will override dicts in ``list1``).
The remaining elements will be summed in order to create a list
which contains elements of both lists.
Expand All @@ -52,12 +52,14 @@ def merge_list(list1, list2):
for list_ in [list1, list2]:
container = dict_map['list{0}'.format(counter)]
for el in list_:
if isinstance(el, dict) and 'name' in el:
key = el['name']
elif isinstance(el, dict) and 'id' in el:
key = el['id']
else:
key = id(el)
# merge by internal python id by default
key = id(el)
# if el is a dict, merge by keys specified in ``identifiers``
if isinstance(el, dict):
for id_key in identifiers:
if id_key in el:
key = el[id_key]
break
container[key] = deepcopy(el)
counter += 1
merged = merge_config(dict_map['list1'], dict_map['list2'])
Expand Down

0 comments on commit 6f712d1

Please sign in to comment.