diff --git a/dpath/__init__.py b/dpath/__init__.py index 2bc9942..eee9985 100644 --- a/dpath/__init__.py +++ b/dpath/__init__.py @@ -347,13 +347,21 @@ def merger(dst, src, _segments=()): continue if flags & MergeType.REPLACE: - try: - target[""] - except TypeError: - segments.set(dst, current_path, found) + if isinstance(target, MutableMapping): + # Mappings are always deep-merged, even under + # REPLACE, so that existing keys (including an + # empty-string key) are preserved. The previous + # implementation probed the target with target[""] + # to detect mappings; on a mapping that raised + # KeyError (or, when the mapping contained an + # empty-string key, succeeded) and silently + # skipped the path, dropping the source data. + merger(dst, found, current_path) continue - except Exception: - raise + # Sequences and other non-mapping targets are replaced + # wholesale by the source. + segments.set(dst, current_path, found) + continue except Exception: # We have a dictionary like thing and we need to attempt to # recursively merge it. diff --git a/tests/test_merge.py b/tests/test_merge.py index a8b638c..9755254 100644 --- a/tests/test_merge.py +++ b/tests/test_merge.py @@ -173,6 +173,21 @@ def test_merge_replace_2(): assert d1['a'][0] == 'a' +def test_merge_replace_empty_string_key_in_dst(): + # Regression: a destination mapping that contains an empty-string key + # must not cause merge(REPLACE) to silently drop the source data. + # The old implementation probed the target with target[""], which + # succeeded on such a mapping and skipped the path entirely. + dst = {"a": {"": "keep", "x": 1}} + src = {"a": {"y": 2}} + + dpath.merge(dst, copy.deepcopy(src), flags=dpath.MergeType.REPLACE) + + assert dst["a"]["y"] == 2, "source data was dropped: %r" % (dst,) + assert dst["a"][""] == "keep", "existing empty-string key lost: %r" % (dst,) + assert dst["a"]["x"] == 1, "existing key lost: %r" % (dst,) + + def test_merge_list(): src = {"l": [1]} p1 = {"l": [2], "v": 1}