py3compat.py
68 lines
| 1.6 KiB
| text/x-python
|
PythonLexer
|
r4740 | # coding: utf-8 | ||
|
r24011 | """Compatibility tricks for Python 3. Mainly to do with unicode. | ||
This file is deprecated and will be removed in a future version. | ||||
""" | ||||
|
r22756 | import platform | ||
|
r27224 | import builtins as builtin_mod | ||
|
r6655 | |||
|
r6716 | from .encoding import DEFAULT_ENCODING | ||
|
r4730 | |||
def decode(s, encoding=None): | ||||
|
r6716 | encoding = encoding or DEFAULT_ENCODING | ||
|
r4730 | return s.decode(encoding, "replace") | ||
|
r27224 | |||
|
r4730 | def encode(u, encoding=None): | ||
|
r6716 | encoding = encoding or DEFAULT_ENCODING | ||
|
r4730 | return u.encode(encoding, "replace") | ||
|
r6651 | |||
|
r4731 | def cast_unicode(s, encoding=None): | ||
if isinstance(s, bytes): | ||||
return decode(s, encoding) | ||||
return s | ||||
|
r19203 | |||
|
r10635 | def safe_unicode(e): | ||
"""unicode(e) with various fallbacks. Used for exceptions, which may not be | ||||
safe to call unicode() on. | ||||
""" | ||||
try: | ||||
|
r25330 | return str(e) | ||
|
r10635 | except UnicodeError: | ||
pass | ||||
try: | ||||
|
r25330 | return repr(e) | ||
|
r10635 | except UnicodeError: | ||
pass | ||||
|
r27224 | return "Unrecoverably corrupt evalue" | ||
|
r10635 | |||
|
r24010 | # keep reference to builtin_mod because the kernel overrides that value | ||
# to forward requests to a frontend. | ||||
|
r27224 | def input(prompt=""): | ||
|
r24010 | return builtin_mod.input(prompt) | ||
def execfile(fname, glob, loc=None, compiler=None): | ||||
loc = loc if (loc is not None) else glob | ||||
|
r27224 | with open(fname, "rb") as f: | ||
|
r24010 | compiler = compiler or compile | ||
|
r27224 | exec(compiler(f.read(), fname, "exec"), glob, loc) | ||
|
r24010 | |||
|
r22756 | PYPY = platform.python_implementation() == "PyPy" | ||
|
r21803 | |||
|
r28480 | |||
|
r25402 | # Cython still rely on that as a Dec 28 2019 | ||
# See https://github.com/cython/cython/pull/3291 and | ||||
# https://github.com/ipython/ipython/issues/12068 | ||||
def no_code(x, encoding=None): | ||||
|
r27224 | return x | ||
|
r25402 | |||
|
r27224 | |||
unicode_to_str = cast_bytes_py2 = no_code | ||||