diff --git a/dpath/__init__.py b/dpath/__init__.py index 2bc9942..9cfdae5 100644 --- a/dpath/__init__.py +++ b/dpath/__init__.py @@ -243,6 +243,10 @@ def f(obj, pair, result): (path, found) = pair if keeper(path, found): + # A selected parent already includes its descendants by reference. + # Reassigning them is unnecessary and would try to mutate tuples. + if segments.has(result, path) and segments.get(result, path) is found: + return segments.set(result, path, found, hints=segments.types(obj, path)) return segments.fold(obj, f, {}) diff --git a/tests/test_merge.py b/tests/test_merge.py index a8b638c..77e1144 100644 --- a/tests/test_merge.py +++ b/tests/test_merge.py @@ -7,6 +7,17 @@ from dpath import MergeType +def test_merge_preserves_tuples_in_source_lists(): + dst = {"foo": []} + src = {"foo": [("bar", "baz")]} + + dpath.merge(dst, src) + + assert dst == src + assert dst["foo"][0] is src["foo"][0] + assert isinstance(src["foo"][0], tuple) + + def test_merge_typesafe_and_separator(): src = { "dict": { diff --git a/tests/test_search.py b/tests/test_search.py index 7219d2b..43bbe24 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -1,6 +1,16 @@ import dpath +def test_search_preserves_selected_tuple_container(): + obj = {"foo": [("bar", {"baz": 1})]} + + result = dpath.search(obj, "**") + + assert result == obj + assert result["foo"] is obj["foo"] + assert isinstance(obj["foo"][0], tuple) + + def test_search_paths_with_separator(): dict = { "a": {