Coverage for src/sensai/util/hash.py: 33%

15 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-13 22:17 +0000

1import pickle 

2import hashlib 

3from typing import Any 

4 

5 

6def pickle_hash(o: Any, algorithm='sha1', with_class_name=False) -> str: 

7 """ 

8 Computes a deterministic hash code based on the contents of the given object 

9 

10 :param o: any picklable object 

11 :param algorithm: the name of a hashing algorithm supported by hashlib 

12 :param with_class_name: if True, prepend o's class name to the returned hex string 

13 :return: the object's hash code as a hex string 

14 """ 

15 s = pickle.dumps(o) 

16 result = hashlib.new(algorithm, s).hexdigest() 

17 if with_class_name: 

18 result = o.__class__.__name__ + result 

19 return result 

20 

21 

22def str_hash(o: Any, algorithm='sha1', with_class_name=False) -> str: 

23 """ 

24 Computes a deterministic hash code based on the string representation of the given object 

25 

26 :param o: any object 

27 :param algorithm: the name of a hashing algorithm supported by hashlib 

28 :param with_class_name: if True, prepend o's class name to the returned hex string 

29 :return: the object's hash code as a hex string 

30 """ 

31 s = str(o) 

32 result = hashlib.new(algorithm, s).hexdigest() 

33 if with_class_name: 

34 result = o.__class__.__name__ + result 

35 return result