Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Missing Keys in patch and revert #149

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
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