pg.object_utils.merge

Accessible via pg.object_utils.merge.

merge(value_list, merge_fn=None)[source]

Merge a list of hierarchical values.

Example:

original = {
    'a': 1,
    'b': 2,
    'c': {
        'd': 'foo',
        'e': 'bar'
    }
}
patch =  {
    'b': 3,
    'd': [1, 2, 3],
    'c': {
        'e': 'bar2',
        'f': 10
    }
}
output = pg.object_utils.merge([original, patch])
assert output == {
    'a': 1,
    # b is updated.
    'b': 3,
    'c': {
        'd': 'foo',
        # e is updated.
        'e': 'bar2',
        # f is added.
        'f': 10
    },
    # d is inserted.
    'd': [1, 2, 3]
})
Return type:

Any

Parameters:
  • value_list – A list of hierarchical values to merge. Later value will be treated as updates if it’s a dict or otherwise a replacement of former value. The merge process will keep input values intact.

  • merge_fn – A function to handle value merge that will be called for updated or added keys. If a branch is added/updated, the root of branch will be passed to merge_fn. the signature of function is: (path, left_value, right_value) -> final_value If a key is only present in src dict, old_value is MISSING_VALUE; If a key is only present in dest dict, new_value is MISSING_VALUE; otherwise both new_value and old_value are filled. If final_value is MISSING_VALUE for a path, it will be removed from its parent collection.

Returns:

A merged value.

Raises:
  • TypeError – If value_list is not a list.

  • KeyError – If new key is found while not allowed.