Skip to content

Commit 6f712d1

Browse files
committed
[utils] Implemented identifiers as parameters in utils.merge_list
This will allow each backend to supply its own list of supported identifiers for the merge_list function.
1 parent 321bab0 commit 6f712d1

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

netjsonconfig/utils.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,13 @@ def merge_config(template, config):
3333
return result
3434

3535

36-
def merge_list(list1, list2):
36+
def merge_list(list1, list2, identifiers=['name', 'id']):
3737
"""
3838
Merges ``list2`` on top of ``list1``.
3939
40-
If both lists contain dictionaries which have keys like
41-
``name`` or ``id`` of equal values, those dicts are merged
42-
(dicts in ``list2`` will override dicts in ``list1``).
40+
If both lists contain dictionaries which have keys specified
41+
in ``identifiers`` which have equal values, those dicts will
42+
be merged (dicts in ``list2`` will override dicts in ``list1``).
4343
The remaining elements will be summed in order to create a list
4444
which contains elements of both lists.
4545
@@ -52,12 +52,14 @@ def merge_list(list1, list2):
5252
for list_ in [list1, list2]:
5353
container = dict_map['list{0}'.format(counter)]
5454
for el in list_:
55-
if isinstance(el, dict) and 'name' in el:
56-
key = el['name']
57-
elif isinstance(el, dict) and 'id' in el:
58-
key = el['id']
59-
else:
60-
key = id(el)
55+
# merge by internal python id by default
56+
key = id(el)
57+
# if el is a dict, merge by keys specified in ``identifiers``
58+
if isinstance(el, dict):
59+
for id_key in identifiers:
60+
if id_key in el:
61+
key = el[id_key]
62+
break
6163
container[key] = deepcopy(el)
6264
counter += 1
6365
merged = merge_config(dict_map['list1'], dict_map['list2'])

0 commit comments

Comments
 (0)