compat.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """
  2. Compatibility module for high-level h5py
  3. """
  4. import sys
  5. from os import fspath, fsencode, fsdecode
  6. from ..version import hdf5_built_version_tuple
  7. WINDOWS_ENCODING = "utf-8" if hdf5_built_version_tuple >= (1, 10, 6) else "mbcs"
  8. def filename_encode(filename):
  9. """
  10. Encode filename for use in the HDF5 library.
  11. Due to how HDF5 handles filenames on different systems, this should be
  12. called on any filenames passed to the HDF5 library. See the documentation on
  13. filenames in h5py for more information.
  14. """
  15. filename = fspath(filename)
  16. if sys.platform == "win32":
  17. if isinstance(filename, str):
  18. return filename.encode(WINDOWS_ENCODING, "strict")
  19. return filename
  20. return fsencode(filename)
  21. def filename_decode(filename):
  22. """
  23. Decode filename used by HDF5 library.
  24. Due to how HDF5 handles filenames on different systems, this should be
  25. called on any filenames passed from the HDF5 library. See the documentation
  26. on filenames in h5py for more information.
  27. """
  28. if sys.platform == "win32":
  29. if isinstance(filename, bytes):
  30. return filename.decode(WINDOWS_ENCODING, "strict")
  31. elif isinstance(filename, str):
  32. return filename
  33. else:
  34. raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
  35. return fsdecode(filename)