compat.py 1.0 KB

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