Skip to content
Closed
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
2 changes: 1 addition & 1 deletion Lib/_pyio.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ def readlines(self, hint=None):
for line in self:
lines.append(line)
n += len(line)
if n >= hint:
if n > hint:
break
return lines

Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_io/test_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,24 @@ def test_readline(self):
with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f:
self.assertRaises(TypeError, f.readline, 5.3)

def test_readlines_hint(self):
# gh-161272: reading stops only once the total size of the lines
# read *exceeds* hint, not when it is equal to it.
all_lines = [b"a\n", b"bb\n", b"ccc\n", b"dddd\n"]
with self.open(os_helper.TESTFN, "wb") as f:
f.writelines(all_lines)
for hint, expected in ((1, all_lines[:1]), (2, all_lines[:2]),
(3, all_lines[:2]), (5, all_lines[:3]),
(9, all_lines), (100, all_lines),
(0, all_lines), (-1, all_lines)):
with self.subTest(hint=hint):
with self.open(os_helper.TESTFN, "rb") as f:
self.assertEqual(f.readlines(hint), expected)
with self.open(os_helper.TESTFN, "rb") as f:
self.assertEqual(f.readlines(), all_lines)
with self.open(os_helper.TESTFN, "r", encoding="ascii") as f:
self.assertEqual(f.readlines(2), ["a\n", "bb\n"])

def test_readline_limit_with_short_read(self):
class Reader(self.IOBase):
data = b"abcdef"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fix an off-by-one in the pure Python implementation of
:meth:`io.IOBase.readlines` (``_pyio``): it now stops reading only once the
total size of the lines read *exceeds* *hint*, as documented and as the C
implementation does. Previously one line fewer was returned when that total
was exactly *hint*.
Loading