GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — adding faq. fix for brackets in path. adding python 3.10 support. adding · FOSSAware/deepdiff@103f2d2

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .github/workflows
    • main.yaml
  • deepdiff
    • diff.py
    • operator.py
    • path.py
  • docs
    • Makefile
    • custom.rst
    • diff.rst
    • diff_doc.rst
    • faq.rst
  • setup.py
  • tests
    • test_delta.py
    • test_operators.py
    • test_path.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.github/workflows/main.yaml‎

Copy file name to clipboardExpand all lines: .github/workflows/main.yaml
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ jobs:
1212
runs-on: ubuntu-latest
1313
strategy:
1414
matrix:
15-
python-version: [3.6, 3.7, 3.8, 3.9]
15+
python-version: [3.6, 3.7, 3.8, 3.9, 3.10]
1616
architecture: ["x64"]
1717

1818
steps:
Collapse file

‎deepdiff/diff.py‎

Copy file name to clipboardExpand all lines: deepdiff/diff.py
+19-5Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1245,16 +1245,30 @@ def _auto_off_cache(self):
12451245

12461246
def _use_custom_operator(self, level):
12471247
"""
1248-
1248+
For each level we check all custom operators.
1249+
If any one of them was a match for the level, we run the diff of the operator.
1250+
If the operator returned True, the operator must have decided these objects should not
1251+
be compared anymore. It might have already reported their results.
1252+
In that case the report will appear in the final results of this diff.
1253+
Otherwise basically the 2 objects in the level are being omitted from the results.
12491254
"""
1250-
used = False
1255+
1256+
# used = False
1257+
1258+
# for operator in self.custom_operators:
1259+
# if operator.match(level):
1260+
# prevent_default = operator.diff(level, self)
1261+
# used = True if prevent_default is None else prevent_default
1262+
1263+
# return used
12511264

12521265
for operator in self.custom_operators:
12531266
if operator.match(level):
1254-
prevent_default = operator.diff(level, self)
1255-
used = True if prevent_default is None else prevent_default
1267+
prevent_default = operator.give_up_diffing(level=level, diff_instance=self)
1268+
if prevent_default:
1269+
return True
12561270

1257-
return used
1271+
return False
12581272

12591273
def _diff(self, level, parents_ids=frozenset(), _original_type=None):
12601274
"""
Collapse file

‎deepdiff/operator.py‎

Copy file name to clipboard
+19-7Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,28 @@
11
import re
2+
from deepdiff.helper import convert_item_or_items_into_compiled_regexes_else_none
23

34

45
class BaseOperator:
56
__operator_name__ = "__base__"
67

7-
def __init__(self, path_regex):
8-
self.path_regex = path_regex
9-
self.regex = re.compile(f"^{self.path_regex}$")
8+
def __init__(self, regex_paths=None, types=None):
9+
if regex_paths:
10+
self.regex_paths = convert_item_or_items_into_compiled_regexes_else_none(regex_paths)
11+
else:
12+
self.regex_paths = None
13+
self.types = types
1014

1115
def match(self, level) -> bool:
12-
matched = re.search(self.regex, level.path()) is not None
13-
return matched
16+
if self.regex_paths:
17+
for pattern in self.regex_paths:
18+
matched = re.search(pattern, level.path()) is not None
19+
if matched:
20+
return True
21+
if self.types:
22+
for type_ in self.types:
23+
if isinstance(level.t1, type_) and isinstance(level.t2, type_):
24+
return True
25+
return False
1426

15-
def diff(self, level, instance) -> bool:
16-
raise NotImplementedError
27+
def give_up_diffing(self, level, diff_instance) -> bool:
28+
raise NotImplementedError('Please implement the diff function.')
Collapse file

‎deepdiff/path.py‎

Copy file name to clipboardExpand all lines: deepdiff/path.py
+29-5Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ class RootCanNotBeModified(ValueError):
1919

2020
def _add_to_elements(elements, elem, inside):
2121
# Ignore private items
22+
if not elem:
23+
return
2224
if not elem.startswith('__'):
2325
try:
2426
elem = literal_eval(elem)
@@ -49,14 +51,31 @@ def _path_to_elements(path, root_element=DEFAULT_FIRST_ELEMENT):
4951
inside = False
5052
prev_char = None
5153
path = path[4:] # removing "root from the beginning"
54+
brackets = []
55+
inside_quotes = False
5256
for char in path:
5357
if prev_char == '\\':
5458
elem += char
59+
elif char in {'"', "'"}:
60+
elem += char
61+
inside_quotes = not inside_quotes
62+
if not inside_quotes:
63+
_add_to_elements(elements, elem, inside)
64+
elem = ''
65+
elif inside_quotes:
66+
elem += char
5567
elif char == '[':
5668
if inside == '.':
5769
_add_to_elements(elements, elem, inside)
58-
inside = '['
59-
elem = ''
70+
inside = '['
71+
elem = ''
72+
# we are already inside. The bracket is a part of the word.
73+
elif inside == '[':
74+
elem += char
75+
else:
76+
inside = '['
77+
brackets.append('[')
78+
elem = ''
6079
elif char == '.':
6180
if inside == '[':
6281
elem += char
@@ -67,9 +86,14 @@ def _path_to_elements(path, root_element=DEFAULT_FIRST_ELEMENT):
6786
inside = '.'
6887
elem = ''
6988
elif char == ']':
70-
_add_to_elements(elements, elem, inside)
71-
elem = ''
72-
inside = False
89+
if brackets and brackets[-1] == '[':
90+
brackets.pop()
91+
if brackets:
92+
elem += char
93+
else:
94+
_add_to_elements(elements, elem, inside)
95+
elem = ''
96+
inside = False
7397
else:
7498
elem += char
7599
prev_char = char
Collapse file

‎docs/Makefile‎

Copy file name to clipboardExpand all lines: docs/Makefile
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
2323

2424
help:
2525
@echo "Please use \`make <target>' where <target> is one of"
26+
@echo " buildme echos what to run to do live builds."
2627
@echo " html to make standalone HTML files"
2728
@echo " dirhtml to make HTML files named index.html in directories"
2829
@echo " singlehtml to make a single large HTML file"
@@ -48,6 +49,9 @@ help:
4849
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
4950
@echo " coverage to run coverage check of the documentation (if enabled)"
5051

52+
buildme:
53+
@echo "Please make sure the .env is pointing to the right path for the build. Then run ./buildme.py"
54+
5155
clean:
5256
rm -rf $(BUILDDIR)/*
5357

Collapse file

‎docs/other.rst‎ ‎docs/custom.rst‎docs/other.rst renamed to docs/custom.rst

Copy file name to clipboardExpand all lines: docs/custom.rst
+76-36Lines changed: 76 additions & 36 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
:doc:`/index`
22

3-
Other Parameters
4-
================
3+
Customized Diff
4+
===============
55

66
.. _iterable_compare_func_label:
77

@@ -122,67 +122,107 @@ For example you could use the level object to further determine if the 2 objects
122122

123123
The level parameter of the iterable_compare_func is only used when ignore_order=False which is the default value for ignore_order.
124124

125+
125126
.. _custom_operators_label:
126127

127128
Custom Operators
128-
---------------------
129+
----------------
129130

130131
Whether two objects are different or not are largely depend on the context. For example, apple and banana are the same
131-
if you are considering whether the
132+
if you are considering whether they are fruits or not.
132133

133-
*custom_operators* is for the job.
134+
In that case, you can pass a *custom_operators* for the job.
134135

135136
To define an custom operator, you just need to inherit a *BaseOperator* and
136-
* implement method
137-
* diff(level: DiffLevel, instance: DeepDiff) -> boolean
138-
* to do custom diff logic with full access to DeepDiff instance
139-
* you can use instance.custom_report_result to record info
140-
* to return a boolean value to determine whether the process
141-
should quit or continue with default behavior
142137

138+
* implement a give_up_diffing method
139+
* give_up_diffing(level: DiffLevel, diff_instance: DeepDiff) -> boolean
140+
141+
If it returns True, then we will give up diffing the 2 objects.
142+
You may or may not use the diff_instance.custom_report_result within this function
143+
to report any diff. If you decide not to report anything, and this
144+
function returns True, then the objects are basically skipped in the results.
145+
146+
* pass regex_paths and types that will be used to decide if the objects are matched.
147+
one the objects are matched, then the give_up_diffing will be run to compare them.
143148

144-
An operator that mapping L2:distance as diff criteria
149+
150+
**Example 1: An operator that mapping L2:distance as diff criteria and reports the distance**
151+
152+
>>> import math
153+
>>>
154+
>>> from typing import List
145155
>>> from deepdiff import DeepDiff
146156
>>> from deepdiff.operator import BaseOperator
147157
>>>
158+
>>>
159+
>>> class L2DistanceDifferWithPreventDefault(BaseOperator):
160+
... def __init__(self, regex_paths: List[str], distance_threshold: float):
161+
... super().__init__(regex_paths)
162+
... self.distance_threshold = distance_threshold
163+
... def _l2_distance(self, c1, c2):
164+
... return math.sqrt(
165+
... (c1["x"] - c2["x"]) ** 2 + (c1["y"] - c2["y"]) ** 2
166+
... )
167+
... def give_up_diffing(self, level, diff_instance):
168+
... l2_distance = self._l2_distance(level.t1, level.t2)
169+
... if l2_distance > self.distance_threshold:
170+
... diff_instance.custom_report_result('distance_too_far', level, {
171+
... "l2_distance": l2_distance
172+
... })
173+
... return True
174+
...
175+
>>>
148176
>>> t1 = {
149177
... "coordinates": [
150178
... {"x": 5, "y": 5},
151179
... {"x": 8, "y": 8}
152180
... ]
153181
... }
154-
...
182+
>>>
155183
>>> t2 = {
156184
... "coordinates": [
157185
... {"x": 6, "y": 6},
158186
... {"x": 88, "y": 88}
159187
... ]
160188
... }
189+
>>> DeepDiff(t1, t2, custom_operators=[L2DistanceDifferWithPreventDefault(
190+
... ["^root\\['coordinates'\\]\\[\\d+\\]$"],
191+
... 1
192+
... )])
193+
{'distance_too_far': {"root['coordinates'][0]": {'l2_distance': 1.4142135623730951}, "root['coordinates'][1]": {'l2_distance': 113.13708498984761}}}
194+
195+
196+
**Example 2: If the objects are subclasses of a certain type, only compare them if their list attributes are not equal sets**
197+
198+
>>> class CustomClass:
199+
... def __init__(self, d: dict, l: list):
200+
... self.dict = d
201+
... self.dict['list'] = l
161202
...
162-
>>> class L2DistanceDifferWithPreventDefault(BaseOperator):
163-
... def __init__(self, distance_threshold):
164-
... self.distance_threshold = distance_threshold
165-
...
166-
... def _l2_distance(self, c1, c2):
167-
... return math.sqrt(
168-
... (c1["x"] - c2["x"]) ** 2 + (c1["y"] - c2["y"]) ** 2
169-
... )
170-
... # you can also override match method
171-
... # def match(self, level):
172-
... # return True
173-
...
174-
... def diff(self, level, diff_instance):
175-
... l2_distance = self._l2_distance(level.t1, level.t2)
176-
... if l2_distance > self.distance_threshold:
177-
... diff_instance.custom_report_result('distance_too_far', level, {
178-
... "l2_distance": l2_distance
179-
... })
180-
... #
181-
... return True
203+
>>>
204+
>>> custom1 = CustomClass(d=dict(a=1, b=2), l=[1, 2, 3])
205+
>>> custom2 = CustomClass(d=dict(c=3, d=4), l=[1, 2, 3, 2])
206+
>>> custom3 = CustomClass(d=dict(a=1, b=2), l=[1, 2, 3, 4])
207+
>>>
208+
>>>
209+
>>> class ListMatchOperator(BaseOperator):
210+
... def give_up_diffing(self, level, diff_instance):
211+
... if set(level.t1.dict['list']) == set(level.t2.dict['list']):
212+
... return True
182213
...
183-
>>> DeepDiff(t1, t2, custom_operators=[L2DistanceDifferWithPreventDefault(1)])
184-
{'distance_too_far': {"root['coordinates'][0]": {'l2_distance': 1.4142135623730951},
185-
"root['coordinates'][1]": {'l2_distance': 113.13708498984761}}}
214+
>>>
215+
>>> DeepDiff(custom1, custom2, custom_operators=[
216+
... ListMatchOperator(types=[CustomClass])
217+
... ])
218+
{}
219+
>>>
220+
>>>
221+
>>> DeepDiff(custom2, custom3, custom_operators=[
222+
... ListMatchOperator(types=[CustomClass])
223+
... ])
224+
{'dictionary_item_added': [root.dict['a'], root.dict['b']], 'dictionary_item_removed': [root.dict['c'], root.dict['d']], 'values_changed': {"root.dict['list'][3]": {'new_value': 4, 'old_value': 2}}}
225+
>>>
186226

187227

188228
Back to :doc:`/index`
Collapse file

‎docs/diff.rst‎

Copy file name to clipboardExpand all lines: docs/diff.rst
+2-1Lines changed: 2 additions & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ DeepDiff
2323
serialization
2424
optimizations
2525
stats
26-
other
26+
custom
27+
faq
2728
troubleshoot
2829

2930
Back to :doc:`/index`
Collapse file

‎docs/diff_doc.rst‎

Copy file name to clipboardExpand all lines: docs/diff_doc.rst
+3-1Lines changed: 3 additions & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
DeepDiff
44
========
55

6-
76
Deep Difference of dictionaries, iterables, strings and almost any other object.
87
It will recursively look for all the changes.
98

@@ -34,6 +33,9 @@ cache_purge_level: int, 0, 1, or 2. default=1
3433
cache_tuning_sample_size : int >= 0, default = 0
3534
:ref:`cache_tuning_sample_size_label` This is an experimental feature. It works hands in hands with the :ref:`cache_size_label`. When cache_tuning_sample_size is set to anything above zero, it will sample the cache usage with the passed sample size and decide whether to use the cache or not. And will turn it back on occasionally during the diffing process. This option can be useful if you are not sure if you need any cache or not. However you will gain much better performance with keeping this parameter zero and running your diff with different cache sizes and benchmarking to find the optimal cache size.
3635

36+
custom_operators : BaseOperator subclasses, default = None
37+
:ref:`custom_operators_label` if you are considering whether they are fruits or not. In that case, you can pass a *custom_operators* for the job.
38+
3739
exclude_paths: list, default = None
3840
:ref:`exclude_paths_label`
3941
List of paths to exclude from the report. If only one item, you can path it as a string.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.