Format: text/x-python
⬇ Download File (1.5 KB)
   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  
  10  
  11  class Unpickler(pickle.Unpickler):
  12      def find_class(self, module: str, name: str) -> Any:
  13          # Python 3.13 moved pathlib implementation out of __init__.py as part of
  14          # generalising its implementation. Ensure that we support loading
  15          # pickles from 3.13 on older version of Python. Since 3.13 maintained a
  16          # compatible API, pickles from older Python work natively on the newer
  17          # version.
  18          if module == 'pathlib._local':
  19              module = 'pathlib'
  20          return super().find_class(module, name)
  21  
  22  
  23  def pickle_load(file):
  24      try:
  25          return Unpickler(file).load()
  26      # Python on Windows don't throw EOF errors for pipes. So reraise them with
  27      # the correct type, which is caught upwards.
  28      except OSError:
  29          if sys.platform == 'win32':
  30              raise EOFError()
  31          raise
  32  
  33  
  34  def pickle_dump(data, file, protocol):
  35      try:
  36          pickle.dump(data, file, protocol)
  37          # On Python 3.3 flush throws sometimes an error even though the writing
  38          # operation should be completed.
  39          file.flush()
  40      # Python on Windows don't throw EPIPE errors for pipes. So reraise them with
  41      # the correct type and error number.
  42      except OSError:
  43          if sys.platform == 'win32':
  44              raise IOError(errno.EPIPE, "Broken pipe")
  45          raise
  46