Debian Codegraph @

docs/deephash_doc.rst

raw
1 :orphan:
2
3 **DeepHash**
4
5 DeepHash calculates the hash of objects based on their contents in a deterministic way.
6 This way 2 objects with the same content should have the same hash.
7
8 The main usage of DeepHash is to calculate the hash of otherwise unhashable objects.
9 For example you can use DeepHash to calculate the hash of a set or a dictionary!
10
11 At the core of it, DeepHash is a deterministic serialization of your object into a string so it
12 can be passed to a hash function. By default it uses SHA256. You have the option to pass any other hashing function to be used instead.
13
14 **Import**
15 >>> from deepdiff import DeepHash
16
17 **Parameters**
18
19 obj : any object, The object to be hashed based on its content.
20
21
22 apply_hash: Boolean, default = True
23 DeepHash at its core is doing deterministic serialization of objects into strings.
24 Then it hashes the string.
25 The only time you want the apply_hash to be False is if you want to know what
26 the string representation of your object is BEFORE it gets hashed.
27
28
29 exclude_types: list, default = None
30 List of object types to exclude from hashing.
31
32
33 exclude_paths: list, default = None
34 List of paths to exclude from the report. If only one item, you can pass it as a string instead of a list containing only one path.
35
36
37 include_paths: list, default = None
38 List of the only paths to include in the report. If only one item, you can pass it as a string.
39
40
41 exclude_regex_paths: list, default = None
42 List of string regex paths or compiled regex paths objects to exclude from the report. If only one item, you can pass it as a string instead of a list containing only one regex path.
43
44
45 exclude_obj_callback
46 function, default = None
47 A function that takes the object and its path and returns a Boolean. If True is returned, the object is excluded from the results, otherwise it is included.
48 This is to give the user a higher level of control than one can achieve via exclude_paths, exclude_regex_paths or other means.
49
50
51 encodings: List, default = None
52 Character encodings to iterate through when we convert bytes into strings. You may want to pass an explicit list of encodings in your objects if you start getting UnicodeDecodeError from DeepHash. Also check out ignore_encoding_errors if you can get away with ignoring these errors and don't want to bother with an explicit list of encodings but it will come at the price of slightly less accuracy of the final results. Example: encodings=["utf-8", "latin-1"]
53
54
55 hashes: dictionary, default = empty dictionary
56 A dictionary of {object or object id: object hash} to start with.
57 Any object that is encountered and it is already in the hashes dictionary or its id is in the hashes dictionary,
58 will re-use the hash that is provided by this dictionary instead of re-calculating
59 its hash. This is typically used when you have a series of objects to be hashed and there might be repeats of the same object.
60
61
62 hasher: function. default = DeepHash.sha256hex
63 hasher is the hashing function. The default is DeepHash.sha256hex.
64 But you can pass another hash function to it if you want.
65 For example a cryptographic hash function or Python's builtin hash function.
66 All it needs is a function that takes the input in string format and returns the hash.
67
68 You can use it by passing: hasher=hash for Python's builtin hash.
69
70 The following alternative is already provided:
71
72 - hasher=DeepHash.sha1hex
73
74 Note that prior to DeepDiff 5.2, Murmur3 was the default hash function.
75 But Murmur3 is removed from DeepDiff dependencies since then.
76
77
78 ignore_repetition: Boolean, default = True
79 If repetitions in an iterable should cause the hash of iterable to be different.
80 Note that the deepdiff diffing functionality lets this to be the default at all times.
81 But if you are using DeepHash directly, you can set this parameter.
82
83
84 ignore_type_in_groups
85 Ignore type changes between members of groups of types. For example if you want to ignore type changes between float and decimals etc. Note that this is a more granular feature. Most of the times the shortcuts provided to you are enough.
86 The shortcuts are ignore_string_type_changes which by default is False and ignore_numeric_type_changes which is by default False. You can read more about those shortcuts in this page. ignore_type_in_groups gives you more control compared to the shortcuts.
87
88 For example lets say you have specifically str and byte datatypes to be ignored for type changes. Then you have a couple of options:
89
90 1. Set ignore_string_type_changes=True which is the default.
91 2. Set ignore_type_in_groups=[(str, bytes)]. Here you are saying if we detect one type to be str and the other one bytes, do not report them as type change. It is exactly as passing ignore_type_in_groups=[DeepDiff.strings] or ignore_type_in_groups=DeepDiff.strings .
92
93 Now what if you want also typeA and typeB to be ignored when comparing agains each other?
94
95 1. ignore_type_in_groups=[DeepDiff.strings, (typeA, typeB)]
96 2. or ignore_type_in_groups=[(str, bytes), (typeA, typeB)]
97
98 ignore_string_type_changes: Boolean, default = True
99 string type conversions should not affect the hash output when this is set to True.
100 For example "Hello" and b"Hello" should produce the same hash.
101
102 By setting it to True, both the string and bytes of hello return the same hash.
103
104
105 ignore_numeric_type_changes: Boolean, default = False
106 numeric type conversions should not affect the hash output when this is set to True.
107 For example 10, 10.0 and Decimal(10) should produce the same hash.
108 When ignore_numeric_type_changes is set to True, all numbers are converted
109 to strings with the precision of significant_digits parameter and number_format_notation notation.
110 If no significant_digits is passed by the user, a default value of 12 is used.
111
112
113 ignore_type_subclasses
114 Use ignore_type_subclasses=True so when ignoring type (class), the subclasses of that class are ignored too.
115
116
117 ignore_string_case
118 Whether to be case-sensitive or not when comparing strings. By settings ignore_string_case=False, strings will be compared case-insensitively.
119
120
121 ignore_private_variables: Boolean, default = True
122 Whether to exclude the private variables in the calculations or not. It only affects variables that start with double underscores (__).
123
124
125 ignore_encoding_errors: Boolean, default = False
126 If you want to get away with UnicodeDecodeError without passing explicit character encodings, set this option to True. If you want to make sure the encoding is done properly, keep this as False and instead pass an explicit list of character encodings to be considered via the encodings parameter.
127
128 ignore_iterable_order: Boolean, default = True
129 If order of items in an iterable should not cause the hash of the iterable to be different.
130
131 number_format_notation : string, default="f"
132 number_format_notation is what defines the meaning of significant digits. The default value of "f" means the digits AFTER the decimal point. "f" stands for fixed point. The other option is "e" which stands for exponent notation or scientific notation.
133
134
135 significant_digits : int >= 0, default=None
136 By default the significant_digits compares only that many digits AFTER the decimal point. However you can set override that by setting the number_format_notation="e" which will make it mean the digits in scientific notation.
137
138 Important: This will affect ANY number comparison when it is set.
139
140 Note: If ignore_numeric_type_changes is set to True and you have left significant_digits to the default of None, it gets automatically set to 12. The reason is that normally when numbers from 2 different types are compared, instead of comparing the values, we only report the type change. However when ignore_numeric_type_changes=True, in order compare numbers from different types to each other, we need to convert them all into strings. The significant_digits will be used to make sure we accurately convert all the numbers into strings in order to report the changes between them.
141
142 Internally it uses "{:.Xf}".format(Your Number) to compare numbers where X=significant_digits when the number_format_notation is left as the default of "f" meaning fixed point.
143
144 Note that "{:.3f}".format(1.1135) = 1.113, but "{:.3f}".format(1.11351) = 1.114
145
146 For Decimals, Python's format rounds 2.5 to 2 and 3.5 to 4 (to the closest even number)
147
148 When you set the number_format_notation="e", we use "{:.Xe}".format(Your Number) where X=significant_digits.
149
150 truncate_datetime: string, default = None
151 Can take value one of 'second', 'minute', 'hour', 'day' and truncate with this value datetime objects before hashing it
152
153
154
155 **Returns**
156 A dictionary of {item: item hash}.
157 If your object is nested, it will build hashes of all the objects it contains too.
158
159
160 .. note::
161 DeepHash output is not like conventional hash functions. It is a dictionary of object IDs to their hashes. This happens because DeepHash calculates the hash of the object and any other objects found within the object in a recursive manner. If you only need the hash of the object you are passing, all you need to do is to do:
162
163 >>> from deepdiff import DeepHash
164 >>> obj = {1: 2, 'a': 'b'}
165 >>> DeepHash(obj)[obj] # doctest: +SKIP
166
167
168 **Examples**
169
170 Let's say you have a dictionary object.
171 >>> from deepdiff import DeepHash
172 >>> obj = {1: 2, 'a': 'b'}
173
174 If you try to hash it:
175 >>> hash(obj)
176 Traceback (most recent call last):
177 File "<stdin>", line 1, in <module>
178 TypeError: unhashable type: 'dict'
179
180 But with DeepHash:
181
182 >>> from deepdiff import DeepHash
183 >>> obj = {1: 2, 'a': 'b'}
184 >>> DeepHash(obj) # doctest: +SKIP
185
186 So what is exactly the hash of obj in this case?
187 DeepHash is calculating the hash of the obj and any other object that obj contains.
188 The output of DeepHash is a dictionary of object IDs to their hashes.
189 In order to get the hash of obj itself, you need to use the object (or the id of object) to get its hash:
190
191 >>> hashes = DeepHash(obj)
192 >>> hashes[obj]
193 'bf5478de322aa033da36bf3bcf9f0599e13a520773f50c6eb9f2487377a7929b'
194
195 Which you can write as:
196
197 >>> hashes = DeepHash(obj)[obj]
198
199 At first it might seem weird why DeepHash(obj)[obj] but remember that DeepHash(obj) is a dictionary of hashes of all other objects that obj contains too.
200
201 If you prefer to use another hashing algorithm, you can pass it using the hasher parameter.
202
203 If you do a deep copy of the obj, it should still give you the same hash:
204
205 >>> from copy import deepcopy
206 >>> obj2 = deepcopy(obj)
207 >>> DeepHash(obj2)[obj2]
208 'bf5478de322aa033da36bf3bcf9f0599e13a520773f50c6eb9f2487377a7929b'
209
210 Note that by default DeepHash will include string type differences. So if your strings were bytes:
211
212 >>> obj3 = {1: 2, b'a': b'b'}
213 >>> DeepHash(obj3)[obj3]
214 '71db3231177d49f78b52a356ca206e6179417b681604d00ed703a077049e3300'
215
216 But if you want the same hash if string types are different, set ignore_string_type_changes to True:
217
218 >>> DeepHash(obj3, ignore_string_type_changes=True)[obj3]
219 'e60c2befb84be625037c75e1e26d0bfc85a0ffc1f3cde9500f68f6eac55e5ad6'
220
221 ignore_numeric_type_changes is by default False too.
222
223 >>> from decimal import Decimal
224 >>> obj1 = {4:10}
225 >>> obj2 = {4.0: Decimal(10.0)}
226 >>> DeepHash(obj1)[4] == DeepHash(obj2)[4.0]
227 False
228
229 But by setting it to True, we can get the same hash.
230
231 >>> DeepHash(obj1, ignore_numeric_type_changes=True)[4] == DeepHash(obj2, ignore_numeric_type_changes=True)[4.0]
232 True
233
234 number_format_notation: String, default = "f"
235 number_format_notation is what defines the meaning of significant digits. The default value of "f" means the digits AFTER the decimal point. "f" stands for fixed point. The other option is "e" which stands for exponent notation or scientific notation.
236
237
238 ignore_string_type_changes: Boolean, default = True
239 By setting it to True, both the string and bytes of hello return the same hash.
240
241 >>> DeepHash(b'hello', ignore_string_type_changes=True)[b'hello']
242 '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
243 >>> DeepHash('hello', ignore_string_type_changes=True)['hello']
244 '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
245
246
247 ignore_numeric_type_changes: Boolean, default = False
248 For example if significant_digits=5, 1.1, Decimal(1.1) are both converted to 1.10000
249
250 That way they both produce the same hash.
251
252 >>> t1 = {1: 1, 2: 2.22}
253 >>> DeepHash(t1)[1]
254 'c1800a30c736483f13615542e7096f7973631fef8ca935ee1ed9f35fb06fd44e'
255 >>> DeepHash(t1, ignore_numeric_type_changes=True)[1] == DeepHash(t1, ignore_numeric_type_changes=True)[1.0]
256 True
257
258 You can pass a list of tuples or list of lists if you have various type groups. When t1 and t2 both fall under one of these type groups, the type change will be ignored. DeepDiff already comes with 2 groups: DeepDiff.strings and DeepDiff.numbers . If you want to pass both:
259
260 >>> from deepdiff import DeepDiff
261 >>> ignore_type_in_groups = [DeepDiff.strings, DeepDiff.numbers]
262
263
264 ignore_type_in_groups example with custom objects:
265
266 >>> class Burrito:
267 ... bread = 'flour'
268 ... def __init__(self):
269 ... self.spicy = True
270 ...
271 >>>
272 >>> class Taco:
273 ... bread = 'flour'
274 ... def __init__(self):
275 ... self.spicy = True
276 ...
277 >>>
278 >>> burrito = Burrito()
279 >>> taco = Taco()
280 >>>
281 >>> burritos = [burrito]
282 >>> tacos = [taco]
283 >>>
284 >>> d1 = DeepHash(burritos, ignore_type_in_groups=[(Taco, Burrito)])
285 >>> d2 = DeepHash(tacos, ignore_type_in_groups=[(Taco, Burrito)])
286 >>> d1[burrito] == d2[taco]
287 True
288
289
290 ignore_type_subclasses
291 Use ignore_type_subclasses=True so when ignoring type (class), the subclasses of that class are ignored too.
292
293 >>> from deepdiff import DeepHash
294 >>>
295 >>> class ClassB:
296 ... def __init__(self, x):
297 ... self.x = x
298 ... def __repr__(self):
299 ... return "obj b"
300 ...
301 >>>
302 >>> class ClassC(ClassB):
303 ... def __repr__(self):
304 ... return "obj c"
305 ...
306 >>> obj_b = ClassB(1)
307 >>> obj_c = ClassC(1)
308 >>>
309 >>> # By default, subclasses are considered part of the type group.
310 ... # ignore_type_in_groups=[(ClassB, )] matches ClassC too since it's a subclass.
311 ... hashes_b = DeepHash(obj_b, ignore_type_in_groups=[(ClassB, )])
312 >>> hashes_c = DeepHash(obj_c, ignore_type_in_groups=[(ClassB, )])
313 >>> hashes_b[obj_b] == hashes_c[obj_c]
314 True
315 >>>
316 >>> # With ignore_type_subclasses=True, only exact type matches count.
317 ... # ClassC no longer matches (ClassB, ) group, so hashes differ.
318 ... hashes_b = DeepHash(obj_b, ignore_type_in_groups=[(ClassB, )], ignore_type_subclasses=True)
319 >>> hashes_c = DeepHash(obj_c, ignore_type_in_groups=[(ClassB, )], ignore_type_subclasses=True)
320 >>> hashes_b[obj_b] != hashes_c[obj_c]
321 True
322
323 ignore_string_case
324 Whether to be case-sensitive or not when comparing strings. By settings ignore_string_case=False, strings will be compared case-insensitively.
325
326 >>> from deepdiff import DeepHash
327 >>> DeepHash('hello')['hello'] == DeepHash('heLLO')['heLLO']
328 False
329 >>> DeepHash('hello', ignore_string_case=True)['hello'] == DeepHash('heLLO', ignore_string_case=True)['heLLO']
330 True
331
332 exclude_obj_callback
333 function, default = None
334 A function that takes the object and its path and returns a Boolean. If True is returned, the object is excluded from the results, otherwise it is included.
335 This is to give the user a higher level of control than one can achieve via exclude_paths, exclude_regex_paths or other means.
336
337 >>> def exclude_obj_callback(obj, path):
338 ... return True if isinstance(obj, str) and obj in ('x', 'y') else False
339 ...
340 >>> dic1 = {"x": 1, "y": 2, "z": 3}
341 >>> t1 = [dic1]
342 >>> t1_hash = DeepHash(t1, exclude_obj_callback=exclude_obj_callback)
343 >>>
344 >>> dic2 = {"z": 3}
345 >>> t2 = [dic2]
346 >>> t2_hash = DeepHash(t2, exclude_obj_callback=exclude_obj_callback)
347 >>>
348 >>> t1_hash[t1] == t2_hash[t2]
349 True
350
351 number_format_notation : string, default="f"
352 When numbers are converted to the string, you have the choices between "f" as fixed point and "e" as scientific notation:
353
354 >>> t1=10002
355 >>> t2=10004
356 >>> t1_hash = DeepHash(t1, significant_digits=3, number_format_notation="f")
357 >>> t2_hash = DeepHash(t2, significant_digits=3, number_format_notation="f")
358 >>>
359 >>> t1_hash[t1] == t2_hash[t2]
360 False
361 >>>
362 >>>
363 >>> # Now we use the scientific notation
364 ... t1_hash = DeepHash(t1, significant_digits=3, number_format_notation="e")
365 >>> t2_hash = DeepHash(t2, significant_digits=3, number_format_notation="e")
366 >>>
367 >>> t1_hash[t1] == t2_hash[t2]
368 True
369
370 Defining your own number_to_string_func
371 Lets say you want the hash of numbers below 100 to be the same for some reason.
372
373 >>> from deepdiff import DeepHash
374 >>> from deepdiff.helper import number_to_string
375 >>> def custom_number_to_string(number, *args, **kwargs):
376 ... number = 100 if number < 100 else number
377 ... return number_to_string(number, *args, **kwargs)
378 ...
379 >>> t1 = [10, 12, 100000]
380 >>> t2 = [50, 63, 100021]
381 >>> t1_hash = DeepHash(t1, significant_digits=3, number_format_notation="e", number_to_string_func=custom_number_to_string)
382 >>> t2_hash = DeepHash(t2, significant_digits=3, number_format_notation="e", number_to_string_func=custom_number_to_string)
383 >>> t1_hash[t1] == t2_hash[t2]
384 True
385
386 So both lists produced the same hash thanks to the low significant digits for 100000 vs 100021 and also the custom_number_to_string that converted all numbers below 100 to be 100!