Debian Codegraph @

docs/custom.rst

raw
1 :doc:`/index`
2
3 Customized Diff
4 ===============
5
6 .. _iterable_compare_func_label:
7
8 Iterable Compare Func
9 ---------------------
10
11 New in DeepDiff 5.5.0
12
13 There are times that we want to guide DeepDiff as to what items to compare with other items. In such cases we can pass a `iterable_compare_func` that takes a function pointer to compare two items. The function takes three parameters (x, y, level) and should return `True` if it is a match, `False` if it is not a match or raise `CannotCompare` if it is unable to compare the two.
14
15
16 For example take the following objects:
17
18
19 Now let's define a compare_func that takes 3 parameters: x, y and level.
20
21 >>> from deepdiff import DeepDiff
22 >>> from deepdiff.helper import CannotCompare
23 >>>
24 >>> t1 = [
25 ... {
26 ... 'id': 1,
27 ... 'value': [1]
28 ... },
29 ... {
30 ... 'id': 2,
31 ... 'value': [7, 8, 1]
32 ... },
33 ... {
34 ... 'id': 3,
35 ... 'value': [7, 8],
36 ... },
37 ... ]
38 >>>
39 >>> t2 = [
40 ... {
41 ... 'id': 2,
42 ... 'value': [7, 8]
43 ... },
44 ... {
45 ... 'id': 3,
46 ... 'value': [7, 8, 1],
47 ... },
48 ... {
49 ... 'id': 1,
50 ... 'value': [1]
51 ... },
52 ... ]
53 >>>
54 >>> DeepDiff(t1, t2)
55 {'values_changed': {"root[0]['id']": {'new_value': 2, 'old_value': 1}, "root[0]['value'][0]": {'new_value': 7, 'old_value': 1}, "root[1]['id']": {'new_value': 3, 'old_value': 2}, "root[2]['id']": {'new_value': 1, 'old_value': 3}, "root[2]['value'][0]": {'new_value': 1, 'old_value': 7}}, 'iterable_item_added': {"root[0]['value'][1]": 8}, 'iterable_item_removed': {"root[2]['value'][1]": 8}}
56
57 As you can see the results are different. Now items with the same ids are compared with each other.
58
59 >>> def compare_func(x, y, level=None):
60 ... try:
61 ... return x['id'] == y['id']
62 ... except Exception:
63 ... raise CannotCompare() from None
64 ...
65 >>> DeepDiff(t1, t2, iterable_compare_func=compare_func)
66 {'iterable_item_added': {"root[2]['value'][2]": 1}, 'iterable_item_removed': {"root[1]['value'][2]": 1}}
67
68 If we set the verbose_level=2, we can see more details.
69
70 >>> DeepDiff(t1, t2, iterable_compare_func=compare_func, verbose_level=2)
71 {'iterable_item_added': {"root[2]['value'][2]": 1}, 'iterable_item_removed': {"root[1]['value'][2]": 1}, 'iterable_item_moved': {'root[0]': {'new_path': 'root[2]', 'value': {'id': 1, 'value': [1]}}, 'root[1]': {'new_path': 'root[0]', 'value': {'id': 2, 'value': [7, 8]}}, 'root[2]': {'new_path': 'root[1]', 'value': {'id': 3, 'value': [7, 8, 1]}}}}
72
73
74 We can also use the level parameter. Levels are explained in the :ref:`tree_view_label`.
75
76 For example you could use the level object to further determine if the 2 objects should be matches or not.
77
78
79 >>> t1 = {
80 ... 'path1': [],
81 ... 'path2': [
82 ... {
83 ... 'id': 1,
84 ... 'value': [1]
85 ... },
86 ... {
87 ... 'id': 2,
88 ... 'value': [7, 8, 1]
89 ... },
90 ... ]
91 ... }
92 >>>
93 >>> t2 = {
94 ... 'path1': [{'pizza'}],
95 ... 'path2': [
96 ... {
97 ... 'id': 2,
98 ... 'value': [7, 8, 1]
99 ... },
100 ... {
101 ... 'id': 1,
102 ... 'value': [1, 2]
103 ... },
104 ... ]
105 ... }
106 >>>
107 >>>
108 >>> def compare_func2(x, y, level):
109 ... if (not isinstance(x, dict) or not isinstance(y, dict)):
110 ... raise CannotCompare
111 ... if(level.path() == "root['path2']"):
112 ... if (x["id"] == y["id"]):
113 ... return True
114 ... return False
115 ...
116 >>>
117 >>> DeepDiff(t1, t2, iterable_compare_func=compare_func2)
118 {'iterable_item_added': {"root['path1'][0]": {'pizza'}, "root['path2'][0]['value'][1]": 2}}
119
120
121 .. note::
122
123 The level parameter of the iterable_compare_func is only used when ignore_order=False which is the default value for ignore_order.
124
125
126 .. _custom_operators_label:
127
128 Custom Operators
129 ----------------
130
131 Whether two objects are different or not largely depends on the context. For example, apples and bananas are the same
132 if you are considering whether they are fruits or not.
133
134 In that case, you can pass a *custom_operators* for the job.
135
136 Custom operators give you a lot of power. In the following examples, we explore various use cases such as:
137
138 - Making DeepDiff report the L2 Distance of items
139 - Only include specific paths in diffing
140 - Making DeepDiff stop diffing once we find the first diff.
141
142 You can use one of the predefined custom operators that come with DeepDiff. Or you can define one yourself.
143
144
145 Built-In Custom Operators
146
147 .. _prefix_or_suffix_operator_label:
148
149 PrefixOrSuffixOperator
150 ......................
151
152
153 This operator will skip strings that are suffix or prefix of each other.
154
155 For example when this operator is used, the two strings of "joe" and "joe's car" will not be reported as different.
156
157 >>> from deepdiff import DeepDiff
158 >>> from deepdiff.operator import PrefixOrSuffixOperator
159 >>> t1 = {
160 ... "key1": ["foo", "bar's food", "jack", "joe"]
161 ... }
162 >>> t2 = {
163 ... "key1": ["foo", "bar", "jill", "joe'car"]
164 ... }
165 >>>
166 >>> DeepDiff(t1, t2)
167 {'values_changed': {"root['key1'][1]": {'new_value': 'bar', 'old_value': "bar's food"}, "root['key1'][2]": {'new_value': 'jill', 'old_value': 'jack'}, "root['key1'][3]": {'new_value': "joe'car", 'old_value': 'joe'}}}
168 >>> DeepDiff(t1, t2, custom_operators=[
169 ... PrefixOrSuffixOperator()
170 ... ])
171 >>>
172 {'values_changed': {"root['key1'][2]": {'new_value': 'jill', 'old_value': 'jack'}}}
173
174
175
176
177 Define A Custom Operator
178 ------------------------
179
180
181 To define a custom operator, you just need to inherit *BaseOperator* or *BaseOperatorPlus*.
182
183 - *BaseOperatorPlus* is our new base operator that can be subclassed and provides the structure to build any custom operator.
184 - *BaseOperator* is our older base class for creating custom operators. It was designed mainly for simple string based regex comparison.
185
186
187 Base Operator Plus
188 ..................
189
190 *BaseOperatorPlus* is our new base operator that can be subclassed and provides the structure to build any custom operator.
191
192 .. code-block:: python
193
194 class BaseOperatorPlus(metaclass=ABCMeta):
195
196 @abstractmethod
197 def match(self, level) -> bool:
198 """
199 Given a level which includes t1 and t2 in the tree view, is this operator a good match to compare t1 and t2?
200 If yes, we will run the give_up_diffing to compare t1 and t2 for this level.
201 """
202 pass
203
204 @abstractmethod
205 def give_up_diffing(self, level, diff_instance: "DeepDiff") -> bool:
206 """
207 Given a level which includes t1 and t2 in the tree view, and the "distance" between l1 and l2.
208 do we consider t1 and t2 to be equal or not. The distance is a number between zero to one and is calculated by DeepDiff to measure how similar objects are.
209 """
210
211 @abstractmethod
212 def normalize_value_for_hashing(self, parent: Any, obj: Any) -> Any:
213 """
214 You can use this function to normalize values for ignore_order=True
215
216 For example, you may want to turn all the words to be lowercase. Then you return obj.lower()
217 """
218 pass
219
220
221 **Example 1: We don't care about the exact GUID values. As long as pairs of strings match GUID regex, we want them to be considered as equals**
222
223 >>> import re
224 ... from typing import Any
225 ... from deepdiff import DeepDiff
226 ... from deepdiff.operator import BaseOperatorPlus
227 ...
228 ...
229 ... d1 = {
230 ... "Name": "SUB_OBJECT_FILES",
231 ... "Values": {
232 ... "Value": [
233 ... "{f254498b-b752-4f35-bef5-6f1844b61eb7}",
234 ... "{7fb2a550-1849-45c0-b273-9aa5e4eb9f2b}",
235 ... "{a9cbecc0-21dc-49ce-8b2c-d36352dae139}"
236 ... ]
237 ... }
238 ... }
239 ...
240 ... d2 = {
241 ... "Name": "SUB_OBJECT_FILES",
242 ... "Values": {
243 ... "Value": [
244 ... "{e5d18917-1a2c-4abe-b601-8ec002629953}",
245 ... "{ea71ba1f-1339-4fae-bc28-a9ce9b8a8c67}",
246 ... "{66bb6192-9cd2-4074-8be1-f2ac52877c70}",
247 ... ]
248 ... }
249 ... }
250 ...
251 ...
252 ... class RemoveGUIDsOperator(BaseOperatorPlus):
253 ... _pattern = r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
254 ... _substitute = "guid"
255 ...
256 ... def match(self, level) -> bool:
257 ... return isinstance(level.t1, str) and isinstance(level.t2, str)
258 ...
259 ... @classmethod
260 ... def _remove_pattern(cls, t: str):
261 ... return re.sub(cls._pattern, cls._substitute, t)
262 ...
263 ... def give_up_diffing(self, level, diff_instance):
264 ... t1 = self._remove_pattern(level.t1)
265 ... t2 = self._remove_pattern(level.t2)
266 ... return t1 == t2
267 ...
268 ... def normalize_value_for_hashing(self, parent: Any, obj: Any) -> Any:
269 ... """
270 ... Used for ignore_order=True
271 ... """
272 ... if isinstance(obj, str):
273 ... return self._remove_pattern(obj)
274 ... return obj
275 ...
276 ...
277 ... operator = RemoveGUIDsOperator()
278 ...
279 >>> diff1 = DeepDiff(d1, d2, custom_operators=[operator], log_stacktrace=True)
280 ... diff1
281 {}
282 >>> diff2 = DeepDiff(d1, d2, ignore_order=True, custom_operators=[operator], log_stacktrace=True)
283 ... diff2
284 {}
285
286
287
288 Base Operator
289 .............
290
291 *BaseOperator* is our older base class for creating custom operators. It was designed mainly for simple string based regex comparison.
292
293
294 .. code-block:: python
295
296 class BaseOperator:
297
298 def __init__(self, regex_paths:Optional[List[str]]=None, types:Optional[List[type]]=None):
299 if regex_paths:
300 self.regex_paths = convert_item_or_items_into_compiled_regexes_else_none(regex_paths)
301 else:
302 self.regex_paths = None
303 self.types = types
304
305 def match(self, level) -> bool:
306 if self.regex_paths:
307 for pattern in self.regex_paths:
308 matched = re.search(pattern, level.path()) is not None
309 if matched:
310 return True
311 if self.types:
312 for type_ in self.types:
313 if isinstance(level.t1, type_) and isinstance(level.t2, type_):
314 return True
315 return False
316
317 def give_up_diffing(self, level, diff_instance) -> bool:
318 raise NotImplementedError('Please implement the diff function.')
319
320
321
322 **Example 2: An operator that mapping L2:distance as diff criteria and reports the distance**
323
324 >>> import math
325 >>>
326 >>> from typing import List
327 >>> from deepdiff import DeepDiff
328 >>> from deepdiff.operator import BaseOperator
329 >>>
330 >>>
331 >>> class L2DistanceDifferWithPreventDefault(BaseOperator):
332 ... def __init__(self, regex_paths: List[str], distance_threshold: float):
333 ... super().__init__(regex_paths)
334 ... self.distance_threshold = distance_threshold
335 ... def _l2_distance(self, c1, c2):
336 ... return math.sqrt(
337 ... (c1["x"] - c2["x"]) ** 2 + (c1["y"] - c2["y"]) ** 2
338 ... )
339 ... def give_up_diffing(self, level, diff_instance):
340 ... l2_distance = self._l2_distance(level.t1, level.t2)
341 ... if l2_distance > self.distance_threshold:
342 ... diff_instance.custom_report_result('distance_too_far', level, {
343 ... "l2_distance": l2_distance
344 ... })
345 ... return True
346 ...
347 >>>
348 >>> t1 = {
349 ... "coordinates": [
350 ... {"x": 5, "y": 5},
351 ... {"x": 8, "y": 8}
352 ... ]
353 ... }
354 >>>
355 >>> t2 = {
356 ... "coordinates": [
357 ... {"x": 6, "y": 6},
358 ... {"x": 88, "y": 88}
359 ... ]
360 ... }
361 >>> DeepDiff(t1, t2, custom_operators=[L2DistanceDifferWithPreventDefault(
362 ... ["^root\\['coordinates'\\]\\[\\d+\\]$"],
363 ... 1
364 ... )])
365 {'distance_too_far': {"root['coordinates'][0]": {'l2_distance': 1.4142135623730951}, "root['coordinates'][1]": {'l2_distance': 113.13708498984761}}}
366
367
368 **Example 3: If the objects are subclasses of a certain type, only compare them if their list attributes are not equal sets**
369
370 >>> class CustomClass:
371 ... def __init__(self, d: dict, l: list):
372 ... self.dict = d
373 ... self.dict['list'] = l
374 ...
375 >>>
376 >>> custom1 = CustomClass(d=dict(a=1, b=2), l=[1, 2, 3])
377 >>> custom2 = CustomClass(d=dict(c=3, d=4), l=[1, 2, 3, 2])
378 >>> custom3 = CustomClass(d=dict(a=1, b=2), l=[1, 2, 3, 4])
379 >>>
380 >>>
381 >>> class ListMatchOperator(BaseOperator):
382 ... def give_up_diffing(self, level, diff_instance):
383 ... if set(level.t1.dict['list']) == set(level.t2.dict['list']):
384 ... return True
385 ...
386 >>>
387 >>> DeepDiff(custom1, custom2, custom_operators=[
388 ... ListMatchOperator(types=[CustomClass])
389 ... ])
390 {}
391 >>>
392 >>>
393 >>> DeepDiff(custom2, custom3, custom_operators=[
394 ... ListMatchOperator(types=[CustomClass])
395 ... ])
396 {'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}}}
397 >>>
398
399 **Example 4: Only diff certain paths**
400
401 >>> from deepdiff import DeepDiff
402 >>> class MyOperator:
403 ... def __init__(self, include_paths):
404 ... self.include_paths = include_paths
405 ... def match(self, level) -> bool:
406 ... return True
407 ... def give_up_diffing(self, level, diff_instance) -> bool:
408 ... return level.path() not in self.include_paths
409 ...
410 >>>
411 >>> t1 = {'a': [10, 11], 'b': [20, 21], 'c': [30, 31]}
412 >>> t2 = {'a': [10, 22], 'b': [20, 33], 'c': [30, 44]}
413 >>>
414 >>> DeepDiff(t1, t2, custom_operators=[
415 ... MyOperator(include_paths="root['a'][1]")
416 ... ])
417 {'values_changed': {"root['a'][1]": {'new_value': 22, 'old_value': 11}}}
418
419 **Example 5: Give up further diffing once the first diff is found**
420
421 Sometimes all you care about is that there is a difference between 2 objects and not all the details of what exactly is different.
422 In that case you may want to stop diffing as soon as the first diff is found.
423
424 >>> from deepdiff import DeepDiff
425 >>> class MyOperator:
426 ... def match(self, level) -> bool:
427 ... return True
428 ... def give_up_diffing(self, level, diff_instance) -> bool:
429 ... return any(diff_instance.tree.values())
430 ...
431 >>> t1 = [[1, 2], [3, 4], [5, 6]]
432 >>> t2 = [[1, 3], [3, 5], [5, 7]]
433 >>>
434 >>> DeepDiff(t1, t2, custom_operators=[
435 ... MyOperator()
436 ... ])
437 {'values_changed': {'root[0][1]': {'new_value': 3, 'old_value': 2}}}
438
439
440 Back to :doc:`/index`