diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 770f72c25295cbe..4d991623d80d594 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -499,6 +499,9 @@ def close(self): """ self._closer.close() + def __next__(self): + return next(self.file) + # iter() doesn't use __getattr__ to find the __iter__ method def __iter__(self): # Don't return iter(self.file), but yield from it to avoid closing diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 8ace883d74bb24d..11d71c7b8418763 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -886,6 +886,16 @@ def make_file(): self.assertEqual(l, lines[i]) self.assertEqual(i, len(lines) - 1) + def test_next(self): + lines = [b'spam\n', b'eggs\n', b'beans\n'] + with tempfile.NamedTemporaryFile(mode='w+b') as fd: + fd.write(b''.join(lines)) + fd.seek(0) + + self.assertEqual(list(fd), lines) + with self.assertRaises(StopIteration): + next(fd) + def test_creates_named(self): # NamedTemporaryFile creates files with names f = tempfile.NamedTemporaryFile() diff --git a/Misc/ACKS b/Misc/ACKS index 7f4a9bcbc0f8cdb..dd00da8eeedf880 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -1599,6 +1599,7 @@ Kirill Simonov Nathan Paul Simons Guilherme Simões Adam Simpkins +Seth Sims Karthikeyan Singaravelan Mandeep Singh Ravi Sinha diff --git a/Misc/NEWS.d/next/Library/2020-07-10-14-33-52.bpo-41270.pjUqyd.rst b/Misc/NEWS.d/next/Library/2020-07-10-14-33-52.bpo-41270.pjUqyd.rst new file mode 100644 index 000000000000000..897099bb4fbb640 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-07-10-14-33-52.bpo-41270.pjUqyd.rst @@ -0,0 +1 @@ +Added :func:`tempfile._TemporaryFileWrapper.__next__` so that the object returned by :func:`tempfile.NamedTemporaryFile` can be used to iterate over the contents of the file.