diff --git a/deepdiff/delta.py b/deepdiff/delta.py index 5c5702b8..9119eade 100644 --- a/deepdiff/delta.py +++ b/deepdiff/delta.py @@ -668,10 +668,13 @@ def _do_iterable_opcodes(self): if elem_and_details: elements, parent, parent_to_obj_elem, parent_to_obj_action, obj, elem, action = elem_and_details if parent is None: - parent = self - obj = self.root - parent_to_obj_elem = 'root' - parent_to_obj_action = GETATTR + target_parent = self + target_elem = 'root' + target_action = GETATTR + else: + target_parent = obj + target_elem = elem + target_action = action else: continue # pragma: no cover. Due to cPython peephole optimizer, this line doesn't get covered. https://github.com/nedbat/coveragepy/issues/198 # import pytest; pytest.set_trace() @@ -694,8 +697,8 @@ def _do_iterable_opcodes(self): obj = tuple(transformed) # type: ignore # Making sure that the object is re-instated inside the parent especially if it was immutable # and we had to turn it into a mutable one. In such cases the object has a new id. - self._simple_set_elem_value(obj=parent, path_for_err_reporting=path, elem=parent_to_obj_elem, - value=obj, action=parent_to_obj_action) + self._simple_set_elem_value(obj=target_parent, path_for_err_reporting=path, elem=target_elem, + value=obj, action=target_action) else: obj[:] = transformed # type: ignore diff --git a/tests/test_delta.py b/tests/test_delta.py index a973706e..8536e639 100644 --- a/tests/test_delta.py +++ b/tests/test_delta.py @@ -664,6 +664,21 @@ def test_tuple_iterable_opcodes_with_insert_delete_delta(self): assert "_iterable_opcodes" in delta.diff assert t2 == t1 + delta + def test_nested_tuple_iterable_opcodes_preserves_parent(self): + t1 = {"a": tuple("A B C D H".split()), "b": "keep"} + t2 = {"a": tuple("B C D H Y Z".split()), "b": "keep"} + delta = Delta(DeepDiff(t1, t2), bidirectional=True) + + assert "_iterable_opcodes" in delta.diff + assert t2 == t1 + delta + + nested1 = {"x": {"a": tuple("A B C D H".split()), "b": "keep"}} + nested2 = {"x": {"a": tuple("B C D H Y Z".split()), "b": "keep"}} + nested_delta = Delta(DeepDiff(nested1, nested2), bidirectional=True) + + assert "_iterable_opcodes" in nested_delta.diff + assert nested2 == nested1 + nested_delta + def test_complex_dictionary_keys_removed_delta(self): t1 = {1 + 2j: "a", 3 + 4j: "b"} t2 = {}