_compatibility.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. This module is here to ensure compatibility of Windows/Linux/MacOS and
  3. different Python versions.
  4. """
  5. import errno
  6. import sys
  7. import pickle
  8. from typing import Any
  9. class Unpickler(pickle.Unpickler):
  10. def find_class(self, module: str, name: str) -> Any:
  11. # Python 3.13 moved pathlib implementation out of __init__.py as part of
  12. # generalising its implementation. Ensure that we support loading
  13. # pickles from 3.13 on older version of Python. Since 3.13 maintained a
  14. # compatible API, pickles from older Python work natively on the newer
  15. # version.
  16. if module == 'pathlib._local':
  17. module = 'pathlib'
  18. return super().find_class(module, name)
  19. def pickle_load(file):
  20. try:
  21. return Unpickler(file).load()
  22. # Python on Windows don't throw EOF errors for pipes. So reraise them with
  23. # the correct type, which is caught upwards.
  24. except OSError:
  25. if sys.platform == 'win32':
  26. raise EOFError()
  27. raise
  28. def pickle_dump(data, file, protocol):
  29. try:
  30. pickle.dump(data, file, protocol)
  31. # On Python 3.3 flush throws sometimes an error even though the writing
  32. # operation should be completed.
  33. file.flush()
  34. # Python on Windows don't throw EPIPE errors for pipes. So reraise them with
  35. # the correct type and error number.
  36. except OSError:
  37. if sys.platform == 'win32':
  38. raise IOError(errno.EPIPE, "Broken pipe")
  39. raise