compat.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Python 2/3 compatibility"""
  2. import io
  3. import json
  4. import sys
  5. # Handle reading and writing JSON in UTF-8, on Python 3 and 2.
  6. if sys.version_info[0] >= 3:
  7. # Python 3
  8. def write_json(obj, path, **kwargs):
  9. with open(path, 'w', encoding='utf-8') as f:
  10. json.dump(obj, f, **kwargs)
  11. def read_json(path):
  12. with open(path, 'r', encoding='utf-8') as f:
  13. return json.load(f)
  14. else:
  15. # Python 2
  16. def write_json(obj, path, **kwargs):
  17. with open(path, 'wb') as f:
  18. json.dump(obj, f, encoding='utf-8', **kwargs)
  19. def read_json(path):
  20. with open(path, 'rb') as f:
  21. return json.load(f)
  22. # FileNotFoundError
  23. try:
  24. FileNotFoundError = FileNotFoundError
  25. except NameError:
  26. FileNotFoundError = IOError
  27. if sys.version_info < (3, 6):
  28. from toml import load as _toml_load # noqa: F401
  29. def toml_load(f):
  30. w = io.TextIOWrapper(f, encoding="utf8", newline="")
  31. try:
  32. return _toml_load(w)
  33. finally:
  34. w.detach()
  35. from toml import TomlDecodeError as TOMLDecodeError # noqa: F401
  36. else:
  37. from pip._vendor.tomli import load as toml_load # noqa: F401
  38. from pip._vendor.tomli import TOMLDecodeError # noqa: F401