Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/utils/py3compat.py: 36%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

36 statements  

1# coding: utf-8 

2"""Compatibility tricks for Python 3. Mainly to do with unicode. 

3 

4This file is deprecated and will be removed in a future version. 

5""" 

6 

7import platform 

8import builtins as builtin_mod 

9 

10from .encoding import DEFAULT_ENCODING 

11 

12 

13def decode(s, encoding=None): 

14 encoding = encoding or DEFAULT_ENCODING 

15 return s.decode(encoding, "replace") 

16 

17 

18def encode(u, encoding=None): 

19 encoding = encoding or DEFAULT_ENCODING 

20 return u.encode(encoding, "replace") 

21 

22 

23def cast_unicode(s, encoding=None): 

24 if isinstance(s, bytes): 

25 return decode(s, encoding) 

26 return s 

27 

28 

29def 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. 

48def input(prompt=""): 

49 return builtin_mod.input(prompt) 

50 

51 

52def 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 

59PYPY = platform.python_implementation() == "PyPy" 

60 

61 

62# Cython still rely on that as a Dec 28 2019 

63# See https://github.com/cython/cython/pull/3291 and 

64# https://github.com/ipython/ipython/issues/12068 

65def no_code(x, encoding=None): 

66 return x 

67 

68 

69unicode_to_str = cast_bytes_py2 = no_code