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
29 changes: 25 additions & 4 deletions dictdiffer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,9 @@ def check(key):
return _diff_recursive(first, second, node)


def patch(diff_result, destination, in_place=False):
def patch(
diff_result, destination, in_place=False, allow_missing_keys=False
):
"""Patch the diff result to the destination dictionary.

:param diff_result: Changes returned by ``diff``.
Expand All @@ -283,6 +285,10 @@ def patch(diff_result, destination, in_place=False):
Setting ``in_place=True`` means that patch will apply
the changes directly to and return the destination
structure.
:param allow_missing_keys: By default, trying to remove a missing
key will raise a KeyError. Setting
``allow_missing_keys=True``` will silently
ignore this error.
"""
if not in_place:
destination = deepcopy(destination)
Expand Down Expand Up @@ -314,7 +320,13 @@ def remove(node, changes):
if isinstance(dest, SET_TYPES):
dest -= value
else:
del dest[key]
try:
del dest[key]
except KeyError:
if allow_missing_keys:
pass
else:
raise

patchers = {
REMOVE: remove,
Expand Down Expand Up @@ -368,7 +380,9 @@ def change(node, changes):
yield swappers[action](node, change)


def revert(diff_result, destination, in_place=False):
def revert(
diff_result, destination, in_place=False, allow_missing_keys=False
):
"""Call swap function to revert patched dictionary object.

Usage example:
Expand All @@ -386,5 +400,12 @@ def revert(diff_result, destination, in_place=False):
is returned. Setting ``in_place=True`` means
that revert will apply the changes directly to
and return the destination structure.
:param allow_missing_keys: By default, trying to remove a missing
key will raise a KeyError. Setting
``allow_missing_keys=True``` will silently
ignore this error.
"""
return patch(swap(diff_result), destination, in_place)
return patch(
swap(diff_result), destination, in_place,
allow_missing_keys=allow_missing_keys
)
Loading