Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 56cefa6

Browse files
Issue #23700: Iterator of NamedTemporaryFile now keeps a reference to
NamedTemporaryFile instance. Patch by Bohuslav Kabrda.
1 parent 86fdbf3 commit 56cefa6

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

Lib/tempfile.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,9 @@ def close(self):
426426

427427
# iter() doesn't use __getattr__ to find the __iter__ method
428428
def __iter__(self):
429-
return iter(self.file)
429+
# don't return iter(self.file), but yield from it to avoid closing
430+
# file as long as it's being used as iterator, see issue #23000
431+
yield from iter(self.file)
430432

431433

432434
def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,

Lib/test/test_tempfile.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,19 @@ def test_method_lookup(self):
707707
# No reference cycle was created.
708708
self.assertIsNone(wr())
709709

710+
def test_iter(self):
711+
# Issue #23700: getting iterator from a temporary file should keep
712+
# it alive as long as it's being iterated over
713+
lines = [b'spam\n', b'eggs\n', b'beans\n']
714+
def make_file():
715+
f = tempfile.NamedTemporaryFile(mode='w+b')
716+
f.write(b''.join(lines))
717+
f.seek(0)
718+
return f
719+
for i, l in enumerate(make_file()):
720+
self.assertEqual(l, lines[i])
721+
self.assertEqual(i, len(lines) - 1)
722+
710723
def test_creates_named(self):
711724
# NamedTemporaryFile creates files with names
712725
f = tempfile.NamedTemporaryFile()

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ Core and Builtins
1818
Library
1919
-------
2020

21+
- Issue #23700: Iterator of NamedTemporaryFile now keeps a reference to
22+
NamedTemporaryFile instance. Patch by Bohuslav Kabrda.
23+
2124
- Issue #22903: The fake test case created by unittest.loader when it fails
2225
importing a test module is now picklable.
2326

0 commit comments

Comments
 (0)