Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
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
3 changes: 3 additions & 0 deletions 3 Lib/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions 10 Lib/test/test_tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions 1 Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1599,6 +1599,7 @@ Kirill Simonov
Nathan Paul Simons
Guilherme Simões
Adam Simpkins
Seth Sims
Karthikeyan Singaravelan
Mandeep Singh
Ravi Sinha
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Morty Proxy This is a proxified and sanitized view of the page, visit original site.