From 6eecadc66ed5ba3bd1b4827e3630172094e116d6 Mon Sep 17 00:00:00 2001 From: Miro <200482516+Mirochill@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:45:24 +0200 Subject: [PATCH] patch: support complete root replacements Assisted-by: OpenAI Codex --- CHANGES | 5 +++++ dictdiffer/__init__.py | 13 ++++++++---- docs/index.rst | 21 ++++++++++++++++++ tests/test_dictdiffer.py | 46 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 4 deletions(-) diff --git a/CHANGES b/CHANGES index 4f6baae..39ddac6 100644 --- a/CHANGES +++ b/CHANGES @@ -1,6 +1,11 @@ Changes ======= +Unreleased + +- patch: support complete root replacements and distinguish empty dictionary + keys from the root path. + Version v0.10.0 (released 2026-07-16) - chore(setup): migrate from setuptools to hatchling diff --git a/dictdiffer/__init__.py b/dictdiffer/__init__.py index 230ff9b..0b75496 100644 --- a/dictdiffer/__init__.py +++ b/dictdiffer/__init__.py @@ -130,7 +130,7 @@ def _process_ignore_value(value): return value, elif isinstance(value, list): return tuple(value) - elif not dot_notation and isinstance(value, str): + elif isinstance(value, str) and (not dot_notation or not value): return value, return value @@ -138,7 +138,7 @@ def _process_ignore_value(value): def dotted(node, default_type=list): """Return dotted notation.""" - if dot_notation and \ + if dot_notation and node != [''] and \ all(map(lambda x: isinstance(x, str) and '.' not in x, node)): return '.'.join(node) @@ -287,7 +287,8 @@ def patch(diff_result, destination, in_place=False): before applying the patch, and the copy is returned. Setting ``in_place=True`` means that patch will apply the changes directly to and return the destination - structure. + structure. A change at the root returns a replacement + value, including when ``in_place=True``. """ if not in_place: destination = deepcopy(destination) @@ -303,6 +304,11 @@ def add(node, changes): dest[key] = value def change(node, changes): + nonlocal destination + _, value = changes + if node == '' or node == []: + destination = deepcopy(value) + return dest = dot_lookup(destination, node, parent=True) if isinstance(node, str): last_node = node.split('.')[-1] @@ -310,7 +316,6 @@ def change(node, changes): last_node = node[-1] if isinstance(dest, LIST_TYPES): last_node = int(last_node) - _, value = changes dest[last_node] = value def remove(node, changes): diff --git a/docs/index.rst b/docs/index.rst index b8d011e..5b8d620 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -98,6 +98,27 @@ Let's revert the last changes: reverted = revert(result, patched) assert reverted == first +If the root value changes type, the patch replaces the complete root. Always +use the return value of :func:`.patch`, including with ``in_place=True``: + +.. doctest:: + + >>> from dictdiffer import diff, patch + >>> first = {'items': [1]} + >>> second = [2, 3] + >>> patch(diff(first, second), first, in_place=True) + [2, 3] + >>> first + {'items': [1]} + +A top-level empty dictionary key uses a list path, so it can be distinguished +from the empty path that represents the root: + +.. doctest:: + + >>> list(diff({'': 1}, {'': 2})) + [('change', [''], (1, 2))] + A tolerance can be used to consider closed values as equal. The tolerance parameter only applies for int and float. diff --git a/tests/test_dictdiffer.py b/tests/test_dictdiffer.py index c1152b8..6ee5a65 100644 --- a/tests/test_dictdiffer.py +++ b/tests/test_dictdiffer.py @@ -6,6 +6,7 @@ import unittest from collections import OrderedDict from collections.abc import MutableMapping, MutableSequence +from copy import deepcopy import pytest @@ -13,6 +14,51 @@ from dictdiffer.utils import PathLimit +@pytest.mark.parametrize('dot_notation', [True, False]) +@pytest.mark.parametrize('in_place', [True, False]) +@pytest.mark.parametrize('first,second', [ + ({'value': 1}, [2, 3]), + ([1, 2], {'value': 3}), + ({1, 2}, [3, 4]), + ([1, 2], {3, 4}), + ({'value': 1}, None), + (None, {'value': 2}), +]) +def test_patch_root_replacement(first, second, dot_notation, in_place): + """Patch and revert changes that replace the complete root value.""" + first = deepcopy(first) + second = deepcopy(second) + original = deepcopy(first) + changes = list(diff(first, second, dot_notation=dot_notation)) + patched = patch(changes, first, in_place=in_place) + assert patched == second + assert first == original + assert revert(changes, patched, in_place=in_place) == first + + +@pytest.mark.parametrize('dot_notation', [True, False]) +@pytest.mark.parametrize('first,second', [ + ({'': 1}, {'': 2}), + ({'': []}, {'': [1, 2]}), + ({'': [1, 2]}, {'': []}), + ({'': {'': 1}}, {'': {'': 2}}), +]) +def test_patch_empty_key(first, second, dot_notation): + """An empty dictionary key remains distinct from the root path.""" + changes = list(diff(first, second, dot_notation=dot_notation)) + patched = patch(changes, first) + assert patched == second + assert revert(changes, patched) == first + + +@pytest.mark.parametrize('dot_notation', [True, False]) +@pytest.mark.parametrize('ignore', [{''}, {('',)}, [['']]]) +def test_ignore_empty_key(ignore, dot_notation): + """Ignoring an empty dictionary key survives path disambiguation.""" + assert list(diff({'': 1, 'kept': 2}, {'': 3, 'kept': 2}, + ignore=ignore, dot_notation=dot_notation)) == [] + + class DictDifferTests(unittest.TestCase): def test_without_dot_notation(self): (change1,) = diff({'a': {'x': 1}},