utils.py 907 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import hashlib
  4. import pickle
  5. import sys
  6. from functools import reduce
  7. from typing import TypeVar, List, Tuple, Dict, Any
  8. from uuid import uuid4
  9. T = TypeVar('T')
  10. def unzip(xs: List[Tuple[List[T], List[T]]]) -> Tuple[List[List[T]], List[List[T]]]:
  11. return list(zip(*xs))
  12. def log(msg: str) -> None:
  13. print(msg, file=sys.stderr)
  14. def merge_dicts(*args: Dict) -> Dict[Any, Any]:
  15. return reduce(lambda x, y: {**x, **y}, args)
  16. def uuid_to_str(uuid: uuid4) -> str:
  17. return str(uuid).replace('-', '')
  18. def hash_dict(d: Dict) -> str:
  19. dict_str_rep = '_'.join([f'{key}_{d[key]}' for key in sorted(d.keys())])
  20. return hashlib.sha224(bytearray(dict_str_rep, 'utf8')).hexdigest()
  21. def pickle_object(obj: object, path: str) -> None:
  22. pickle.dump(obj, open(path, 'wb'))
  23. def unpickle(path: str) -> Any:
  24. return pickle.load(open(path, 'rb'))