Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import pprint 

2import reprlib 

3from typing import Any 

4 

5 

6def _try_repr_or_str(obj): 

7 try: 

8 return repr(obj) 

9 except (KeyboardInterrupt, SystemExit): 

10 raise 

11 except BaseException: 

12 return '{}("{}")'.format(type(obj).__name__, obj) 

13 

14 

15def _format_repr_exception(exc: BaseException, obj: Any) -> str: 

16 try: 

17 exc_info = _try_repr_or_str(exc) 

18 except (KeyboardInterrupt, SystemExit): 

19 raise 

20 except BaseException as exc: 

21 exc_info = "unpresentable exception ({})".format(_try_repr_or_str(exc)) 

22 return "<[{} raised in repr()] {} object at 0x{:x}>".format( 

23 exc_info, obj.__class__.__name__, id(obj) 

24 ) 

25 

26 

27def _ellipsize(s: str, maxsize: int) -> str: 

28 if len(s) > maxsize: 

29 i = max(0, (maxsize - 3) // 2) 

30 j = max(0, maxsize - 3 - i) 

31 return s[:i] + "..." + s[len(s) - j :] 

32 return s 

33 

34 

35class SafeRepr(reprlib.Repr): 

36 """subclass of repr.Repr that limits the resulting size of repr() 

37 and includes information on exceptions raised during the call. 

38 """ 

39 

40 def __init__(self, maxsize: int) -> None: 

41 super().__init__() 

42 self.maxstring = maxsize 

43 self.maxsize = maxsize 

44 

45 def repr(self, x: Any) -> str: 

46 try: 

47 s = super().repr(x) 

48 except (KeyboardInterrupt, SystemExit): 

49 raise 

50 except BaseException as exc: 

51 s = _format_repr_exception(exc, x) 

52 return _ellipsize(s, self.maxsize) 

53 

54 def repr_instance(self, x: Any, level: int) -> str: 

55 try: 

56 s = repr(x) 

57 except (KeyboardInterrupt, SystemExit): 

58 raise 

59 except BaseException as exc: 

60 s = _format_repr_exception(exc, x) 

61 return _ellipsize(s, self.maxsize) 

62 

63 

64def safeformat(obj: Any) -> str: 

65 """return a pretty printed string for the given object. 

66 Failing __repr__ functions of user instances will be represented 

67 with a short exception info. 

68 """ 

69 try: 

70 return pprint.pformat(obj) 

71 except Exception as exc: 

72 return _format_repr_exception(exc, obj) 

73 

74 

75def saferepr(obj: Any, maxsize: int = 240) -> str: 

76 """return a size-limited safe repr-string for the given object. 

77 Failing __repr__ functions of user instances will be represented 

78 with a short exception info and 'saferepr' generally takes 

79 care to never raise exceptions itself. This function is a wrapper 

80 around the Repr/reprlib functionality of the standard 2.6 lib. 

81 """ 

82 return SafeRepr(maxsize).repr(obj)