compat.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. Compatibility module for high-level h5py
  3. """
  4. import os
  5. import sys
  6. from ..version import hdf5_built_version_tuple
  7. # HDF5 supported passing paths as UTF-8 for Windows from 1.10.6, but this
  8. # was broken again in 1.14.4 - https://github.com/HDFGroup/hdf5/issues/5037 .
  9. # The change was reverted in 1.14.6.
  10. if (1, 14, 4) <= hdf5_built_version_tuple < (1, 14, 6):
  11. WINDOWS_ENCODING = "mbcs"
  12. else:
  13. WINDOWS_ENCODING = "utf-8"
  14. def filename_encode(filename):
  15. """
  16. Encode filename for use in the HDF5 library.
  17. Due to how HDF5 handles filenames on different systems, this should be
  18. called on any filenames passed to the HDF5 library. See the documentation on
  19. filenames in h5py for more information.
  20. """
  21. filename = os.fspath(filename)
  22. if sys.platform == "win32" and isinstance(filename, str):
  23. return filename.encode(WINDOWS_ENCODING, "strict")
  24. else:
  25. return os.fsencode(filename)
  26. def filename_decode(filename):
  27. """
  28. Decode filename used by HDF5 library.
  29. Due to how HDF5 handles filenames on different systems, this should be
  30. called on any filenames passed from the HDF5 library. See the documentation
  31. on filenames in h5py for more information.
  32. """
  33. if not isinstance(filename, (str, bytes)):
  34. raise TypeError(f"expect bytes or str, not {type(filename).__name__}")
  35. if sys.platform == "win32" and isinstance(filename, bytes):
  36. return filename.decode(WINDOWS_ENCODING, "strict")
  37. else:
  38. return os.fsdecode(filename)