Skip to content

Fix merge(REPLACE) silently dropping source data for mappings with an empty-string key - #217

Open
TrueFurina wants to merge 1 commit into
dpath-maintainers:masterfrom
TrueFurina:fix/merge-replace-empty-string-key
Open

TrueFurina wants to merge 1 commit into
dpath-maintainers:masterfrom
TrueFurina:fix/merge-replace-empty-string-key

Conversation

@TrueFurina

@TrueFurina TrueFurina commented Nov 10, 2026 •

Copy link
Copy Markdown

Summary

dpath.merge(dst, src, flags=dpath.MergeType.REPLACE) used target[""] to decide
whether the destination node was a mapping. That probe was wrong in two ways:/n

  • On a normal mapping it raised KeyError, which was caught and fell through to a
    recursive merge (acceptable, but incidental).
  • On a mapping that contained an empty-string key, target[""] succeeded,
    so the except branches never ran and the path was silently skipped -- the
    source data at that path was dropped with no error.

Reproduction (before the fix)

import dpath, copy
dst = {'a': {'': 'keep', 'x': 1}}
src = {'a': {'y': 2}}
dpath.merge(dst, copy.deepcopy(src), flags=dpath.MergeType.REPLACE)
assert dst['a']['y'] == 2   # KeyError: 'y' before fix

Fix

Replace the probe with an explicit isinstance(target, MutableMapping) check:/n* mappings are always deep-merged (existing keys, including an empty-string key,
are preserved);

  • only non-mapping targets (e.g. sequences) are replaced wholesale by the source.

This leaves the documented REPLACE behavior for lists and the default dict
deep-merge unchanged. A regression test (test_merge_replace_empty_string_key_in_dst)
is included; the full suite (80 tests) passes.


  • submitted by Dream et AI

… empty-string key

merge(dst, src, flags=MergeType.REPLACE) used `target[""]` to detect whether the
destination node was a mapping. On a mapping that raised KeyError (or, when the
mapping actually contained an empty-string key, *succeeded*) the path was silently
skipped, so the source data at that path was dropped with no error.

Replace the probe with an explicit isinstance() check: mappings are always
deep-merged (matching the existing default/dict behavior, so existing keys including
an empty-string key are preserved), and only non-mapping targets (e.g. sequences)
are replaced wholesale. This keeps the documented REPLACE-for-lists behavior and
the default dict deep-merge unchanged.

Adds a regression test (test_merge_replace_empty_string_key_in_dst).

Co-authored-by: LLM
@TrueFurina TrueFurina changed the title x Fix merge(REPLACE) silently dropping source data for mappings with an empty-string key Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant