Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions Lib/reprlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ def repr_dict(self, x, level):
def repr_str(self, x, level):
s = builtins.repr(x[:self.maxstring])
if len(s) > self.maxstring:
i = max(0, (self.maxstring-3)//2)
j = max(0, self.maxstring-3-i)
i = max(0, (self.maxstring-len(self.fillvalue))//2)
j = max(0, self.maxstring-len(self.fillvalue)-i)
s = builtins.repr(x[:i] + x[len(x)-j:])
s = s[:i] + self.fillvalue + s[len(s)-j:]
return s
Expand All @@ -198,8 +198,8 @@ def repr_int(self, x, level):
return (f'<{x.__class__.__name__} instance with roughly {k} '
f'digits (limit at {max_digits}) at 0x{id(x):x}>')
if len(s) > self.maxlong:
i = max(0, (self.maxlong-3)//2)
j = max(0, self.maxlong-3-i)
i = max(0, (self.maxlong-len(self.fillvalue))//2)
j = max(0, self.maxlong-len(self.fillvalue)-i)
s = s[:i] + self.fillvalue + s[len(s)-j:]
return s

Expand All @@ -211,8 +211,8 @@ def repr_instance(self, x, level):
except Exception:
return '<%s instance at %#x>' % (x.__class__.__name__, id(x))
if len(s) > self.maxother:
i = max(0, (self.maxother-3)//2)
j = max(0, self.maxother-3-i)
i = max(0, (self.maxother-len(self.fillvalue))//2)
j = max(0, self.maxother-len(self.fillvalue)-i)
s = s[:i] + self.fillvalue + s[len(s)-j:]
return s

Expand Down
17 changes: 17 additions & 0 deletions Lib/test/test_reprlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,23 @@ def test_instance(self):
self.assertEndsWith(s, ">")
self.assertIn(s.find("..."), [12, 13])

def test_truncation_with_custom_fillvalue(self):
# The truncated repr must fit the limit whatever the fillvalue length.
eq = self.assertEqual
s = 'abcdefghijklmnopqrstuvwxyz'
n = 12345678901234567890
i = ClassWithRepr('x' * 100)

r1 = Repr(maxstring=10, maxlong=10, maxother=10, fillvalue='…')
eq(r1.repr(s), "'abc…wxyz'")
eq(r1.repr(n), '1234…67890')
eq(r1.repr(i), "Clas…xxx')")

r2 = Repr(maxstring=10, maxlong=10, maxother=10, fillvalue='<snip>')
eq(r2.repr(s), "'a<snip>z'")
eq(r2.repr(n), '12<snip>90')
eq(r2.repr(i), "Cl<snip>')")

def test_lambda(self):
r = repr(lambda x: x)
self.assertStartsWith(r, "<function ReprTests.test_lambda.<locals>.<lambda")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :class:`reprlib.Repr` truncation of strings, integers and other objects
when a custom :attr:`~reprlib.Repr.fillvalue` is not three characters long.
The result now fits :attr:`~reprlib.Repr.maxstring`,
:attr:`~reprlib.Repr.maxlong` and :attr:`~reprlib.Repr.maxother`.
Loading