Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
@@ -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
Expand Down
13 changes: 9 additions & 4 deletions dictdiffer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ 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

ignore = type(ignore)(_process_ignore_value(value) for value in ignore)

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)
Expand Down Expand Up @@ -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)
Expand All @@ -303,14 +304,18 @@ 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]
else:
last_node = node[-1]
if isinstance(dest, LIST_TYPES):
last_node = int(last_node)
_, value = changes
dest[last_node] = value

def remove(node, changes):
Expand Down
21 changes: 21 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
46 changes: 46 additions & 0 deletions tests/test_dictdiffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,59 @@
import unittest
from collections import OrderedDict
from collections.abc import MutableMapping, MutableSequence
from copy import deepcopy

import pytest

from dictdiffer import HAS_NUMPY, diff, dot_lookup, patch, revert, swap
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}},
Expand Down