Debian Codegraph @

docs/delta.rst

raw
1 .. _delta_label:
2
3 Delta
4 =====
5
6 DeepDiff Delta is a directed delta that when applied to t1 can yield t2 where delta is the difference between t1 and t2.
7 Delta objects are like git commits but for structured data.
8 You can convert the diff results into Delta objects, store the deltas, and later apply to other objects.
9
10 .. note::
11 If you plan to generate Delta objects from the DeepDiff result, and ignore_order=True, you need to also set the report_repetition=True.
12
13 **Parameters**
14
15 diff : Delta dictionary, Delta dump payload or a DeepDiff object, default=None.
16 :ref:`delta_diff_label` is the content to be loaded.
17
18 delta_path : String, default=None.
19 :ref:`delta_path_label` is the local path to the delta dump file to be loaded
20
21 delta_file : File Object, default=None.
22 :ref:`delta_file_label` is the file object containing the delta data.
23
24 delta_diff : Delta diff, default=None.
25 This is a slightly different diff than the output of DeepDiff. When Delta object is initiated from the DeepDiff output, it transforms the diff into a slightly different structure that is more suitable for delta. You can find that object via delta.diff.
26 It is the same object that is serialized when you create a delta dump. If you already have the delta_diff object, you can pass it to Delta via the delta_diff parameter.
27
28 flat_dict_list : List of flat dictionaries, default=None,
29 :ref:`flat_dict_list_label` can be used to load the delta object from a list of flat dictionaries.
30
31 .. note::
32 You need to pass only one of the diff, delta_path, or delta_file parameters.
33
34 deserializer : Deserializer function, default=pickle_load
35 :ref:`delta_deserializer_label` is the function to deserialize the delta content. The default is the pickle_load function that comes with DeepDiff.
36
37 serializer : Serializer function, default=pickle_dump
38 :ref:`delta_serializer_label` is the function to serialize the delta content into a format that can be stored. The default is the pickle_dump function that comes with DeepDiff.
39
40 log_errors : Boolean, default=True
41 Whether to log the errors or not when applying the delta object.
42
43 raise_errors : Boolean, default=False
44 :ref:`raise_errors_label`
45 Whether to raise errors or not when applying a delta object.
46
47 mutate : Boolean, default=False.
48 :ref:`delta_mutate_label` defines whether to mutate the original object when adding the delta to it or not.
49 Note that this parameter is not always successful in mutating. For example if your original object
50 is an immutable type such as a frozenset or a tuple, mutation will not succeed.
51 Hence it is recommended to keep this parameter as the default value of False unless you are sure
52 that you do not have immutable objects. There is a small overhead of doing deepcopy on the original
53 object when mutate=False. If performance is a concern and modifying the original object is not a big deal,
54 set the mutate=True but always reassign the output back to the original object.
55
56 safe_to_import : Set, default=None.
57 :ref:`delta_safe_to_import_label` is a set of modules that needs to be explicitly white listed to be loaded
58 Example: {'mymodule.MyClass', 'decimal.Decimal'}
59 Note that this set will be added to the basic set of modules that are already white listed.
60 The set of what is already white listed can be found in deepdiff.serialization.SAFE_TO_IMPORT
61
62 bidirectional : Boolean, default=False
63 :ref:`delta_verify_symmetry_label` is used to verify that the original value of items are the same as when the delta was created. Note that in order for this option to work, the delta object will need to store more data and thus the size of the object will increase. Let's say that the diff object says root[0] changed value from X to Y. If you create the delta with the default value of bidirectional=False, then what delta will store is root[0] = Y. And if this delta was applied to an object that has any root[0] value, it will still set the root[0] to Y. However if bidirectional=True, then the delta object will store also that the original value of root[0] was X and if you try to apply the delta to an object that has root[0] of any value other than X, it will notify you.
64
65 force : Boolean, default=False
66 :ref:`delta_force_label` is used to force apply a delta to objects that have a different structure than what the delta was originally created from.
67
68 always_include_values : Boolean, default=False
69 :ref:`always_include_values_label` is used to make sure the delta objects includes the values that were changed. Sometime Delta tries to be efficient not include the values when it can get away with it. By setting this parameter to True, you ensure that the Delta object will include the values.
70
71 .. _delta_fill:
72
73 fill : Any, default=No Fill
74 This is only relevant if `force` is set. This parameter only applies when force is set and trying to fill an existing array. If the index of the array being applied is larger than the length of the array this value will be used to fill empty spaces of the array to extend it in order to add the new value. If this parameter is not set, the items will get dropped and the array not extended. If this parameter is set with a callable function, it will get called each time a fill item is needed. It will be provided with three arguments: first argument is the array being filled, second argument is the value that is being added to the array, the third argument is the path that is being added.
75 Example function: `def fill(obj, value, path): return "Camry" if "car" in path else None`
76
77
78 **Returns**
79
80 A delta object that can be added to t1 to recreate t2.
81
82 Delta objects can contain the following vocabulary:
83
84 iterable_item_added
85 iterable_item_moved
86 iterable_item_removed
87 set_item_added
88 set_item_removed
89 dictionary_item_added
90 dictionary_item_removed
91 attribute_added
92 attribute_removed
93 type_changes
94 values_changed
95 iterable_items_added_at_indexes
96 iterable_items_removed_at_indexes
97
98
99 .. _delta_diff_label:
100
101 Diff to load in Delta
102 ---------------------
103
104 diff : Delta dictionary, Delta dump payload or a DeepDiff object, default=None.
105 diff is the content to be loaded.
106
107 >>> from deepdiff import DeepDiff, Delta
108 >>> from pprint import pprint
109 >>>
110 >>> t1 = [1, 2, 3]
111 >>> t2 = ['a', 2, 3, 4]
112 >>> diff = DeepDiff(t1, t2)
113 >>> diff
114 {'type_changes': {'root[0]': {'old_type': <class 'int'>, 'new_type': <class 'str'>, 'old_value': 1, 'new_value': 'a'}}, 'iterable_item_added': {'root[3]': 4}}
115 >>> delta = Delta(diff)
116 >>> delta # doctest: +SKIP
117 <Delta: {"type_changes":{"root[0]":{"old_type":"int","new_type":"str","new_value":"a"}},"iterable_item_added":{"root[3]":4}}>
118
119 Applying the delta object to t1 will yield t2:
120
121 >>> t1 + delta
122 ['a', 2, 3, 4]
123 >>> t1 + delta == t2
124 True
125
126 If we want to subtract a delta, we need to create a bidirectional delta:
127
128 >>> delta = Delta(diff, bidirectional=True)
129 >>> t2 - delta
130 [1, 2, 3]
131 >>> t2 - delta == t1
132 True
133
134 Now let's dump the delta object so we can store it.
135
136 >>> dump = delta.dumps()
137 >>>
138 >>> dump # doctest: +SKIP
139
140 The dumps() function gives us the serialized content of the delta in the form of bytes. We could store it however we want. Or we could use the dump(file_object) to write the dump to the file_object instead. But before we try the dump(file_object) method, let's create a new Delta object and reapply it to t1 and see if we still get t2:
141
142 >>> delta2 = Delta(dump)
143 >>> t1 + delta2 == t2
144 True
145 >>>
146
147 .. _delta_path_label:
148
149 Delta Path parameter
150 --------------------
151
152 Ok now we can try the dumps(file_object). It does what you expect:
153
154 >>> with open('/tmp/delta1', 'wb') as dump_file:
155 ... delta.dump(dump_file)
156 ...
157
158 And we use the delta_path parameter to load the delta
159
160 >>> delta3 = Delta(delta_path='/tmp/delta1')
161
162 It still gives us the same result when applied.
163
164 >>> t1 + delta3 == t2
165 True
166
167
168 .. _delta_file_label:
169
170 Delta File parameter
171 --------------------
172
173 You can also pass a file object containing the delta dump:
174
175 >>> with open('/tmp/delta1', 'rb') as dump_file:
176 ... delta4 = Delta(delta_file=dump_file)
177 ...
178 >>> t1 + delta4 == t2
179 True
180
181
182 .. _flat_dict_list_label:
183
184 Flat Dict List
185 --------------
186
187 You can create a delta object from the list of flat dictionaries that are produced via :ref:`to_flat_dicts_label`. Read more on :ref:`delta_from_flat_dicts_label`.
188
189 .. _flat_rows_list_label:
190
191 Flat Rows List
192 --------------
193
194 You can create a delta object from the list of flat dictionaries that are produced via :ref:`delta_to_flat_rows_label`. Read more on :ref:`delta_to_flat_rows_label`.
195
196
197 .. _delta_deserializer_label:
198
199 Delta Deserializer
200 ------------------
201
202 DeepDiff by default uses a restricted Python pickle function to deserialize the Delta dumps. Read more about :ref:`delta_dump_safety_label`.
203
204 The user of Delta can decide to switch the serializer and deserializer to their custom ones. The serializer and deserializer parameters can be used exactly for that reason. The best way to come up with your own serializer and deserializer is to take a look at the `pickle_dump and pickle_load functions in the serializer module <https://github.com/seperman/deepdiff/serialization.py>`_
205
206 .. _delta_json_deserializer_label:
207
208 Json Deserializer for Delta
209 ```````````````````````````
210
211 If all you deal with are Json serializable objects, you can use json for serialization.
212
213 >>> from deepdiff import DeepDiff, Delta
214 >>> from deepdiff.serialization import json_dumps, json_loads
215 >>> t1 = {"a": 1}
216 >>> t2 = {"a": 2}
217 >>>
218 >>> diff = DeepDiff(t1, t2)
219 >>> delta = Delta(diff, serializer=json_dumps)
220 >>> dump = delta.dumps()
221 >>> dump
222 '{"values_changed":{"root[\'a\']":{"new_value":2}}}'
223 >>> delta_reloaded = Delta(dump, deserializer=json_loads)
224 >>> t2 == delta_reloaded + t1
225 True
226
227
228 .. note::
229
230 Json is very limited and easily you can get to deltas that are not json serializable. You will probably want to extend the Python's Json serializer to support your needs.
231
232 >>> import json
233 >>> t1 = {"a": 1}
234 >>> t2 = {"a": None}
235 >>> diff = DeepDiff(t1, t2)
236 >>> diff
237 {'type_changes': {"root['a']": {'old_type': <class 'int'>, 'new_type': <class 'NoneType'>, 'old_value': 1, 'new_value': None}}}
238 >>> Delta(diff, serializer=json.dumps) # doctest: +SKIP
239 <Delta: {"type_changes":{"root['a']":{"old_type":"int","new_type":"NoneType","new_value":null}}}>
240 >>> delta = Delta(diff, serializer=json.dumps)
241 >>> dump = delta.dumps() # doctest: +ELLIPSIS
242 Traceback (most recent call last):
243 ...
244 TypeError: Object of type type is not JSON serializable...
245
246 .. _delta_serializer_label:
247
248 Delta Serializer
249 ----------------
250
251 DeepDiff uses pickle to serialize delta objects by default. Please take a look at the :ref:`delta_deserializer_label` for more information.
252
253
254 .. _to_flat_dicts_label:
255
256 Delta Serialize To Flat Dictionaries
257 ------------------------------------
258
259 Read about :ref:`delta_to_flat_dicts_label`
260
261 .. _delta_dump_safety_label:
262
263 Delta Dump Safety
264 -----------------
265
266 Delta by default uses Python's pickle to serialize and deserialize. While the unrestricted use of pickle is not safe as noted in the `pickle's documentation <https://docs.python.org/3/library/pickle.html>`_ , DeepDiff's Delta is written with extra care to `restrict the globals <https://docs.python.org/3/library/pickle.html#restricting-globals>`_ and hence mitigate this security risk.
267
268 In fact only a few Python object types are allowed by default. The user of DeepDiff can pass additional types using the :ref:`delta_safe_to_import_label` to allow further object types that need to be allowed.
269
270
271 .. _delta_mutate_label:
272
273 Delta Mutate parameter
274 ----------------------
275
276 mutate : Boolean, default=False.
277 delta_mutate defines whether to mutate the original object when adding the delta to it or not.
278 Note that this parameter is not always successful in mutating. For example if your original object
279 is an immutable type such as a frozenset or a tuple, mutation will not succeed.
280 Hence it is recommended to keep this parameter as the default value of False unless you are sure
281 that you do not have immutable objects. There is a small overhead of doing deepcopy on the original
282 object when mutate=False. If performance is a concern and modifying the original object is not a big deal,
283 set the mutate=True but always reassign the output back to the original object.
284
285 For example:
286
287 >>> t1 = [1, 2, [3, 5, 6]]
288 >>> t2 = [2, 3, [3, 6, 8]]
289
290 >>> diff = DeepDiff(t1, t2, ignore_order=True, report_repetition=True)
291 >>> diff
292 {'values_changed': {'root[0]': {'new_value': 3, 'old_value': 1}, 'root[2][1]': {'new_value': 8, 'old_value': 5}}}
293 >>> delta = Delta(diff)
294 >>> delta # doctest: +SKIP
295 <Delta: {"values_changed":{"root[0]":{"new_value":3,"new_path":"root[1]"},"root[2][1]":{"new_value":8,"new_path":"root[2][2]"}}}>
296
297 Note that we can apply delta to objects different than the original objects they were made from:
298
299 >>> t3 = ["a", 2, [3, "b", "c"]]
300 >>> t3 + delta
301 [3, 2, [3, 8, 'c']]
302
303 If we check t3, it is still the same as the original value of t3:
304
305 >>> t3
306 ['a', 2, [3, 'b', 'c']]
307
308 Now let's make the delta with mutate=True
309
310 >>> delta2 = Delta(diff, mutate=True)
311 >>> t3 + delta2
312 [3, 2, [3, 8, 'c']]
313 >>> t3
314 [3, 2, [3, 8, 'c']]
315
316 Applying the delta to t3 mutated the t3 itself in this case!
317
318
319 .. _delta_and_numpy_label:
320
321 Delta and Numpy
322 ---------------
323
324 >>> from deepdiff import DeepDiff, Delta
325 >>> import numpy as np
326 >>> t1 = np.array([1, 2, 3, 5])
327 >>> t2 = np.array([2, 2, 7, 5])
328 >>> diff = DeepDiff(t1, t2)
329 >>> diff
330 {'values_changed': {'root[0]': {'new_value': np.int64(2), 'old_value': np.int64(1)}, 'root[2]': {'new_value': np.int64(7), 'old_value': np.int64(3)}}}
331 >>> delta = Delta(diff)
332
333 .. note::
334 When applying delta to Numpy arrays, make sure to put the delta object first and the numpy array second. This is because Numpy array overrides the + operator and thus DeepDiff's Delta won't be able to be applied.
335
336 >>> t1 + delta
337 Traceback (most recent call last):
338 File "<stdin>", line 1, in <module>
339 raise DeltaNumpyOperatorOverrideError(DELTA_NUMPY_OPERATOR_OVERRIDE_MSG)
340 deepdiff.delta.DeltaNumpyOperatorOverrideError: A numpy ndarray is most likely being added to a delta. Due to Numpy override the + operator, you can only do: delta + ndarray and NOT ndarray + delta
341
342 Let's put the delta first then:
343
344 >>> delta + t1
345 array([2, 2, 7, 5])
346 >>> delta + t2 == t2
347 array([ True, True, True, True])
348
349
350 .. note::
351 You can apply a delta that was created from normal Python objects to Numpy arrays. But it is not recommended.
352
353 .. _raise_errors_label:
354
355 Delta Raise Errors parameter
356 ----------------------------
357
358 raise_errors : Boolean, default=False
359 Whether to raise errors or not when applying a delta object.
360
361 >>> from deepdiff import DeepDiff, Delta
362 >>> t1 = [1, 2, [3, 5, 6]]
363 >>> t2 = [2, 3, [3, 6, 8]]
364 >>> diff = DeepDiff(t1, t2, ignore_order=True, report_repetition=True)
365 >>> delta = Delta(diff, raise_errors=False)
366
367 Now let's apply the delta to a very different object:
368
369 >>> t3 = [1, 2, 3, 5]
370 >>> t4 = t3 + delta # doctest: +SKIP
371
372 We get a log message that it was unable to get the item at root[2][1]. We get the message since by default log_errors=True
373
374 Let's see what t4 is now:
375
376 >>> t4 # doctest: +SKIP
377 [3, 2, 3, 5]
378
379 So the delta was partially applied on t3.
380
381 Now let's set the raise_errors=True
382
383 >>> delta2 = Delta(diff, raise_errors=True)
384 >>>
385 >>> t3 + delta2 # doctest: +ELLIPSIS
386 Traceback (most recent call last):
387 ...
388 deepdiff.delta.DeltaError: Unable to get the item at root[2][1]
389
390
391 .. _delta_safe_to_import_label:
392
393 Delta Safe To Import parameter
394 ------------------------------
395
396 safe_to_import : Set, default=None.
397 safe_to_import is a set of modules that needs to be explicitly white listed to be loaded
398 Example: {'mymodule.MyClass', 'decimal.Decimal'}
399 Note that this set will be added to the basic set of modules that are already white listed.
400
401
402 As noted in :ref:`delta_dump_safety_label` and :ref:`delta_deserializer_label`, DeepDiff's Delta takes safety very seriously and thus limits the globals that can be deserialized when importing. However on occasions that you need a specific type (class) that needs to be used in delta objects, you need to pass it to the Delta via safe_to_import parameter.
403
404 The set of what is already white listed can be found in deepdiff.serialization.SAFE_TO_IMPORT
405 At the time of writing this document, this list consists of:
406
407 >>> from deepdiff.serialization import SAFE_TO_IMPORT
408 >>> from pprint import pprint
409 >>> pprint(SAFE_TO_IMPORT) # doctest: +SKIP
410 frozenset({'builtins.None',
411 'builtins.bin',
412 'builtins.bool',
413 ...})
414
415 If you want to pass any other argument to safe_to_import, you will need to put the full path to the type as it appears in the sys.modules
416
417 For example let's say you have a package call mypackage and has a module called mymodule. If you check the sys.modules, the address to this module must be mypackage.mymodule. In order for Delta to be able to serialize this object via pickle, first of all it has to be `picklable <https://docs.python.org/3/library/pickle.html#object.__reduce__>`_.
418
419 >>> diff = DeepDiff(t1, t2)
420 >>> delta = Delta(diff)
421 >>> dump = delta.dumps()
422
423 The dump at this point is serialized via Pickle and can be written to disc if needed.
424
425 Later when you want to load this dump, by default Delta will block you from importing anything that is NOT in deepdiff.serialization.SAFE_TO_IMPORT . In fact it will show you this error message when trying to load this dump:
426
427 deepdiff.serialization.ForbiddenModule: Module 'builtins.type' is forbidden. You need to explicitly pass it by passing a safe_to_import parameter
428
429 In order to let Delta know that this specific module is safe to import, you will need to pass it to Delta during loading of this dump:
430
431 >>> delta = Delta(dump, safe_to_import={'mypackage.mymodule'})
432
433 .. note ::
434
435 If you pass a custom deserializer to Delta, DeepDiff will pass safe_to_import parameter to the custom deserializer if that deserializer takes safe_to_import as a parameter in its definition.
436 For example if you just use json.loads as deserializer, the safe_to_import items won't be passed to it since json.loads does not have such a parameter.
437
438
439 .. _delta_verify_symmetry_label:
440
441 Delta Verify Symmetry parameter
442 -------------------------------
443
444 bidirectional : Boolean, default=False
445 bidirectional is used to to include all the required information so that we can use the delta object both for addition and subtraction. It will also check that the object you are adding the delta to, has the same values as the original object that the delta was created from.
446
447 It complains if the object is not what it expected to be.
448
449
450 >>> from deepdiff import DeepDiff, Delta
451 >>> t1 = [1]
452 >>> t2 = [2]
453 >>> t3 = [3]
454 >>>
455 >>> diff = DeepDiff(t1, t2)
456 >>>
457 >>> delta2 = Delta(diff, raise_errors=False, bidirectional=True)
458 >>> t4 = delta2 + t3 # doctest: +SKIP
459 >>> t4 # doctest: +SKIP
460 [2]
461
462 And if you had set raise_errors=True, then it would have raised the error in addition to logging it.
463
464
465 .. _delta_force_label:
466
467 Delta Force
468 -----------
469
470 force : Boolean, default=False
471 force is used to force apply a delta to objects that have a different structure than what the delta was originally created from.
472
473
474 >>> from deepdiff import DeepDiff, Delta
475 >>> t1 = {
476 ... 'x': {
477 ... 'y': [1, 2, 3]
478 ... },
479 ... 'q': {
480 ... 'r': 'abc',
481 ... }
482 ... }
483 >>>
484 >>> t2 = {
485 ... 'x': {
486 ... 'y': [1, 2, 3, 4]
487 ... },
488 ... 'q': {
489 ... 'r': 'abc',
490 ... 't': 0.5,
491 ... }
492 ... }
493 >>>
494 >>> diff = DeepDiff(t1, t2)
495 >>> diff
496 {'dictionary_item_added': ["root['q']['t']"], 'iterable_item_added': {"root['x']['y'][3]": 4}}
497 >>> delta = Delta(diff)
498 >>> {} + delta # doctest: +SKIP
499 {}
500
501 Once we set the force to be True
502
503 >>> delta = Delta(diff, force=True)
504 >>> {} + delta
505 {'x': {'y': {3: 4}}, 'q': {'t': 0.5}}
506
507 Notice that the force attribute does not know the original object at ['x']['y'] was supposed to be a list, so it assumes it was a dictionary.
508
509
510 .. _always_include_values_label:
511
512 Always Include Values
513 ---------------------
514
515 always_include_values is used to make sure the delta objects includes the values that were changed. Sometime Delta tries to be efficient not include the values when it can get away with it. By setting this parameter to True, you ensure that the Delta object will include the values.
516
517 For example, when the type of an object changes, if we can easily convert from one type to the other, the Delta object does not include the values:
518
519
520 >>> from deepdiff import DeepDiff, Delta
521 >>> diff = DeepDiff(t1=[1, 2], t2=[1, '2'])
522 >>> diff
523 {'type_changes': {'root[1]': {'old_type': <class 'int'>, 'new_type': <class 'str'>, 'old_value': 2, 'new_value': '2'}}}
524 >>> delta=Delta(diff)
525 >>> delta # doctest: +SKIP
526 <Delta: {"type_changes":{"root[1]":{"old_type":"int","new_type":"str"}}}>
527
528 As you can see the delta object does not include the values that were changed. Now let's pass always_include_values=True:
529
530 >>> delta=Delta(diff, always_include_values=True)
531 >>> delta.diff
532 {'type_changes': {'root[1]': {'old_type': <class 'int'>, 'new_type': <class 'str'>, 'new_value': '2'}}}
533
534 If we want to make sure the old values stay with delta, we pass bidirectional=True. By doing so we can also use the delta object to subtract from other objects.
535
536 >>> delta=Delta(diff, always_include_values=True, bidirectional=True)
537 >>> delta.diff
538 {'type_changes': {'root[1]': {'old_type': <class 'int'>, 'new_type': <class 'str'>, 'old_value': 2, 'new_value': '2'}}}
539