1 """Redo the builtin repr() (representation) but with limits on most sizes."""
3 __all__
= ["Repr","repr"]
6 from itertools
import islice
24 return self
.repr1(x
, self
.maxlevel
)
26 def repr1(self
, x
, level
):
27 typename
= type(x
).__name
__
29 parts
= typename
.split()
30 typename
= '_'.join(parts
)
31 if hasattr(self
, 'repr_' + typename
):
32 return getattr(self
, 'repr_' + typename
)(x
, level
)
34 return self
.repr_instance(x
, level
)
36 def _repr_iterable(self
, x
, level
, left
, right
, maxiter
, trail
=''):
43 pieces
= [repr1(elem
, newlevel
) for elem
in islice(x
, maxiter
)]
44 if n
> maxiter
: pieces
.append('...')
46 if n
== 1 and trail
: right
= trail
+ right
47 return '%s%s%s' % (left
, s
, right
)
49 def repr_tuple(self
, x
, level
):
50 return self
._repr
_iterable
(x
, level
, '(', ')', self
.maxtuple
, ',')
52 def repr_list(self
, x
, level
):
53 return self
._repr
_iterable
(x
, level
, '[', ']', self
.maxlist
)
55 def repr_array(self
, x
, level
):
56 header
= "array('%s', [" % x
.typecode
57 return self
._repr
_iterable
(x
, level
, header
, '])', self
.maxarray
)
59 def repr_set(self
, x
, level
):
60 x
= _possibly_sorted(x
)
61 return self
._repr
_iterable
(x
, level
, 'set([', '])', self
.maxset
)
63 def repr_frozenset(self
, x
, level
):
64 x
= _possibly_sorted(x
)
65 return self
._repr
_iterable
(x
, level
, 'frozenset([', '])',
68 def repr_deque(self
, x
, level
):
69 return self
._repr
_iterable
(x
, level
, 'deque([', '])', self
.maxdeque
)
71 def repr_dict(self
, x
, level
):
73 if n
== 0: return '{}'
74 if level
<= 0: return '{...}'
78 for key
in islice(_possibly_sorted(x
), self
.maxdict
):
79 keyrepr
= repr1(key
, newlevel
)
80 valrepr
= repr1(x
[key
], newlevel
)
81 pieces
.append('%s: %s' % (keyrepr
, valrepr
))
82 if n
> self
.maxdict
: pieces
.append('...')
86 def repr_str(self
, x
, level
):
87 s
= builtins
.repr(x
[:self
.maxstring
])
88 if len(s
) > self
.maxstring
:
89 i
= max(0, (self
.maxstring
-3)//2)
90 j
= max(0, self
.maxstring
-3-i
)
91 s
= builtins
.repr(x
[:i
] + x
[len(x
)-j
:])
92 s
= s
[:i
] + '...' + s
[len(s
)-j
:]
95 def repr_int(self
, x
, level
):
96 s
= builtins
.repr(x
) # XXX Hope this isn't too slow...
97 if len(s
) > self
.maxlong
:
98 i
= max(0, (self
.maxlong
-3)//2)
99 j
= max(0, self
.maxlong
-3-i
)
100 s
= s
[:i
] + '...' + s
[len(s
)-j
:]
103 def repr_instance(self
, x
, level
):
106 # Bugs in x.__repr__() can cause arbitrary
107 # exceptions -- then make up something
109 return '<%s instance at %x>' % (x
.__class
__.__name
__, id(x
))
110 if len(s
) > self
.maxother
:
111 i
= max(0, (self
.maxother
-3)//2)
112 j
= max(0, self
.maxother
-3-i
)
113 s
= s
[:i
] + '...' + s
[len(s
)-j
:]
117 def _possibly_sorted(x
):
118 # Since not all sequences of items can be sorted and comparison
119 # functions may raise arbitrary exceptions, return an unsorted
120 # sequence in that case.