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