Skip to content

Commit 78365b8

Browse files
gh-91078: Return None from TarFile.next when the tarfile is empty (GH-91850)
Co-authored-by: Irit Katriel <[email protected]>
1 parent 7796d31 commit 78365b8

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

Lib/tarfile.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2339,6 +2339,8 @@ def next(self):
23392339

23402340
# Advance the file pointer.
23412341
if self.offset != self.fileobj.tell():
2342+
if self.offset == 0:
2343+
return None
23422344
self.fileobj.seek(self.offset - 1)
23432345
if not self.fileobj.read(1):
23442346
raise ReadError("unexpected end of data")

Lib/test/test_tarfile.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,18 @@ def test_zlib_error_does_not_leak(self):
734734
with self.assertRaises(tarfile.ReadError):
735735
tarfile.open(self.tarname)
736736

737+
def test_next_on_empty_tarfile(self):
738+
fd = io.BytesIO()
739+
tf = tarfile.open(fileobj=fd, mode="w")
740+
tf.close()
741+
742+
fd.seek(0)
743+
with tarfile.open(fileobj=fd, mode="r|") as tf:
744+
self.assertEqual(tf.next(), None)
745+
746+
fd.seek(0)
747+
with tarfile.open(fileobj=fd, mode="r") as tf:
748+
self.assertEqual(tf.next(), None)
737749

738750
class MiscReadTest(MiscReadTestBase, unittest.TestCase):
739751
test_fail_comp = None
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:meth:`TarFile.next` now returns ``None`` when called on an empty tarfile.

0 commit comments

Comments
 (0)