py3compat.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # coding: utf-8
  2. """Compatibility tricks for Python 3. Mainly to do with unicode.
  3. This file is deprecated and will be removed in a future version.
  4. """
  5. import platform
  6. import builtins as builtin_mod
  7. from .encoding import DEFAULT_ENCODING
  8. def decode(s, encoding=None):
  9. encoding = encoding or DEFAULT_ENCODING
  10. return s.decode(encoding, "replace")
  11. def encode(u, encoding=None):
  12. encoding = encoding or DEFAULT_ENCODING
  13. return u.encode(encoding, "replace")
  14. def cast_unicode(s, encoding=None):
  15. if isinstance(s, bytes):
  16. return decode(s, encoding)
  17. return s
  18. def safe_unicode(e):
  19. """unicode(e) with various fallbacks. Used for exceptions, which may not be
  20. safe to call unicode() on.
  21. """
  22. try:
  23. return str(e)
  24. except UnicodeError:
  25. pass
  26. try:
  27. return repr(e)
  28. except UnicodeError:
  29. pass
  30. return "Unrecoverably corrupt evalue"
  31. # keep reference to builtin_mod because the kernel overrides that value
  32. # to forward requests to a frontend.
  33. def input(prompt=""):
  34. return builtin_mod.input(prompt)
  35. def execfile(fname, glob, loc=None, compiler=None):
  36. loc = loc if (loc is not None) else glob
  37. with open(fname, "rb") as f:
  38. compiler = compiler or compile
  39. exec(compiler(f.read(), fname, "exec"), glob, loc)
  40. PYPY = platform.python_implementation() == "PyPy"
  41. # Cython still rely on that as a Dec 28 2019
  42. # See https://github.com/cython/cython/pull/3291 and
  43. # https://github.com/ipython/ipython/issues/12068
  44. def no_code(x, encoding=None):
  45. return x
  46. unicode_to_str = cast_bytes_py2 = no_code