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

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

34 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 

11from typing import Optional 

12 

13 

14def decode(s: bytes, encoding: str | None = None) -> str: 

15 encoding = encoding or DEFAULT_ENCODING 

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

17 

18 

19def encode(u: str, encoding: Optional[str]=None) -> bytes: 

20 encoding = encoding or DEFAULT_ENCODING 

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

22 

23 

24def cast_unicode(s: str | bytes, encoding: Optional[str]=None) -> str: 

25 if isinstance(s, bytes): 

26 return decode(s, encoding) 

27 return s 

28 

29 

30def safe_unicode(e): 

31 """unicode(e) with various fallbacks. Used for exceptions, which may not be 

32 safe to call unicode() on. 

33 """ 

34 try: 

35 return str(e) 

36 except UnicodeError: 

37 pass 

38 

39 try: 

40 return repr(e) 

41 except UnicodeError: 

42 pass 

43 

44 return "Unrecoverably corrupt evalue" 

45 

46 

47# keep reference to builtin_mod because the kernel overrides that value 

48# to forward requests to a frontend. 

49def input(prompt=""): 

50 return builtin_mod.input(prompt) 

51 

52 

53def execfile(fname, glob, loc=None, compiler=None): 

54 loc = loc if (loc is not None) else glob 

55 with open(fname, "rb") as f: 

56 compiler = compiler or compile 

57 exec(compiler(f.read(), fname, "exec"), glob, loc) 

58 

59 

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