py3compat.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. from typing import Optional
  9. def decode(s: bytes, encoding: str | None = None) -> str:
  10. encoding = encoding or DEFAULT_ENCODING
  11. return s.decode(encoding, "replace")
  12. def encode(u: str, encoding: Optional[str]=None) -> bytes:
  13. encoding = encoding or DEFAULT_ENCODING
  14. return u.encode(encoding, "replace")
  15. def cast_unicode(s: str | bytes, encoding: Optional[str]=None) -> str:
  16. if isinstance(s, bytes):
  17. return decode(s, encoding)
  18. return s
  19. def safe_unicode(e):
  20. """unicode(e) with various fallbacks. Used for exceptions, which may not be
  21. safe to call unicode() on.
  22. """
  23. try:
  24. return str(e)
  25. except UnicodeError:
  26. pass
  27. try:
  28. return repr(e)
  29. except UnicodeError:
  30. pass
  31. return "Unrecoverably corrupt evalue"
  32. # keep reference to builtin_mod because the kernel overrides that value
  33. # to forward requests to a frontend.
  34. def input(prompt=""):
  35. return builtin_mod.input(prompt)
  36. def execfile(fname, glob, loc=None, compiler=None):
  37. loc = loc if (loc is not None) else glob
  38. with open(fname, "rb") as f:
  39. compiler = compiler or compile
  40. exec(compiler(f.read(), fname, "exec"), glob, loc)
  41. PYPY = platform.python_implementation() == "PyPy"