diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2015-03-19 15:23:15 +0200 |
---|---|---|
committer | Serhiy Storchaka <storchaka@gmail.com> | 2015-03-19 15:23:15 +0200 |
commit | 56cefa69ee919559cf3ca2388d12371c24402df3 (patch) | |
tree | 5fc0f839259759a19ca05b5a68072a6ad00bce8c /Lib | |
parent | 86fdbf3152f2c19c483da5cce4b4d74539d1407b (diff) | |
download | cpython-git-56cefa69ee919559cf3ca2388d12371c24402df3.tar.gz |
Issue #23700: Iterator of NamedTemporaryFile now keeps a reference to
NamedTemporaryFile instance. Patch by Bohuslav Kabrda.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/tempfile.py | 4 | ||||
-rw-r--r-- | Lib/test/test_tempfile.py | 13 |
2 files changed, 16 insertions, 1 deletions
diff --git a/Lib/tempfile.py b/Lib/tempfile.py index b6eeca3b1a..8352c38a0d 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -426,7 +426,9 @@ class _TemporaryFileWrapper: # iter() doesn't use __getattr__ to find the __iter__ method def __iter__(self): - return iter(self.file) + # don't return iter(self.file), but yield from it to avoid closing + # file as long as it's being used as iterator, see issue #23000 + yield from iter(self.file) def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 2e10fddae0..576cf4d450 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -707,6 +707,19 @@ class TestNamedTemporaryFile(BaseTestCase): # No reference cycle was created. self.assertIsNone(wr()) + def test_iter(self): + # Issue #23700: getting iterator from a temporary file should keep + # it alive as long as it's being iterated over + lines = [b'spam\n', b'eggs\n', b'beans\n'] + def make_file(): + f = tempfile.NamedTemporaryFile(mode='w+b') + f.write(b''.join(lines)) + f.seek(0) + return f + for i, l in enumerate(make_file()): + self.assertEqual(l, lines[i]) + self.assertEqual(i, len(lines) - 1) + def test_creates_named(self): # NamedTemporaryFile creates files with names f = tempfile.NamedTemporaryFile() |