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 import platform 7 import builtins as builtin_mod 8 9 from .encoding import DEFAULT_ENCODING 10 11 12 def decode(s, encoding=None): 13 encoding = encoding or DEFAULT_ENCODING 14 return s.decode(encoding, "replace") 15 16 17 def encode(u, encoding=None): 18 encoding = encoding or DEFAULT_ENCODING 19 return u.encode(encoding, "replace") 20 21 22 def cast_unicode(s, encoding=None): 23 if isinstance(s, bytes): 24 return decode(s, encoding) 25 return s 26 27 28 def safe_unicode(e): 29 """unicode(e) with various fallbacks. Used for exceptions, which may not be 30 safe to call unicode() on. 31 """ 32 try: 33 return str(e) 34 except UnicodeError: 35 pass 36 37 try: 38 return repr(e) 39 except UnicodeError: 40 pass 41 42 return "Unrecoverably corrupt evalue" 43 44 45 # keep reference to builtin_mod because the kernel overrides that value 46 # to forward requests to a frontend. 47 def input(prompt=""): 48 return builtin_mod.input(prompt) 49 50 51 def execfile(fname, glob, loc=None, compiler=None): 52 loc = loc if (loc is not None) else glob 53 with open(fname, "rb") as f: 54 compiler = compiler or compile 55 exec(compiler(f.read(), fname, "exec"), glob, loc) 56 57 58 PYPY = platform.python_implementation() == "PyPy" 59 60 61 # Cython still rely on that as a Dec 28 2019 62 # See https://github.com/cython/cython/pull/3291 and 63 # https://github.com/ipython/ipython/issues/12068 64 def no_code(x, encoding=None): 65 return x 66 67 68 unicode_to_str = cast_bytes_py2 = no_code 69