2
2
import reprlib
3
3
4
4
5
- def _call_and_format_exception (call , x , * args ):
5
+ def _format_repr_exception (exc , obj ):
6
+ exc_name = type (exc ).__name__
6
7
try :
7
- # Try the vanilla repr and make sure that the result is a string
8
- return call (x , * args )
9
- except Exception as exc :
10
- exc_name = type (exc ).__name__
11
- try :
12
- exc_info = str (exc )
13
- except Exception :
14
- exc_info = "unknown"
15
- return '<[{}("{}") raised in repr()] {} object at 0x{:x}>' .format (
16
- exc_name , exc_info , x .__class__ .__name__ , id (x )
17
- )
8
+ exc_info = str (exc )
9
+ except Exception :
10
+ exc_info = "unknown"
11
+ return '<[{}("{}") raised in repr()] {} object at 0x{:x}>' .format (
12
+ exc_name , exc_info , obj .__class__ .__name__ , id (obj )
13
+ )
14
+
15
+
16
+ def _ellipsize (s , maxsize ):
17
+ if len (s ) > maxsize :
18
+ i = max (0 , (maxsize - 3 ) // 2 )
19
+ j = max (0 , maxsize - 3 - i )
20
+ return s [:i ] + "..." + s [len (s ) - j :]
21
+ return s
18
22
19
23
20
24
class SafeRepr (reprlib .Repr ):
@@ -28,26 +32,29 @@ def __init__(self, maxsize):
28
32
self .maxsize = maxsize
29
33
30
34
def repr (self , x ):
31
- return self ._callhelper (reprlib .Repr .repr , self , x )
35
+ try :
36
+ s = super ().repr (x )
37
+ except Exception as exc :
38
+ s = _format_repr_exception (exc , x )
39
+ return _ellipsize (s , self .maxsize )
32
40
33
41
def repr_instance (self , x , level ):
34
- return self ._callhelper (repr , x )
35
-
36
- def _callhelper (self , call , x , * args ):
37
- s = _call_and_format_exception (call , x , * args )
38
- if len (s ) > self .maxsize :
39
- i = max (0 , (self .maxsize - 3 ) // 2 )
40
- j = max (0 , self .maxsize - 3 - i )
41
- s = s [:i ] + "..." + s [len (s ) - j :]
42
- return s
42
+ try :
43
+ s = repr (x )
44
+ except Exception as exc :
45
+ s = _format_repr_exception (exc , x )
46
+ return _ellipsize (s , self .maxsize )
43
47
44
48
45
49
def safeformat (obj ):
46
50
"""return a pretty printed string for the given object.
47
51
Failing __repr__ functions of user instances will be represented
48
52
with a short exception info.
49
53
"""
50
- return _call_and_format_exception (pprint .pformat , obj )
54
+ try :
55
+ return pprint .pformat (obj )
56
+ except Exception as exc :
57
+ return _format_repr_exception (exc , obj )
51
58
52
59
53
60
def saferepr (obj , maxsize = 240 ):
0 commit comments