diff options
author | Georg Brandl <georg@python.org> | 2010-07-31 20:08:15 (GMT) |
---|---|---|
committer | Georg Brandl <georg@python.org> | 2010-07-31 20:08:15 (GMT) |
commit | 6cb7b6593ee03aedebae1bc9bd0f76912efa275a (patch) | |
tree | 30793f9f226d6e647e4bd3a9c6d14d3f24a9f775 /Lib | |
parent | e42a59daec40d1238a0189cde735f97aebe2d0b7 (diff) | |
download | cpython-6cb7b6593ee03aedebae1bc9bd0f76912efa275a.zip cpython-6cb7b6593ee03aedebae1bc9bd0f76912efa275a.tar.gz cpython-6cb7b6593ee03aedebae1bc9bd0f76912efa275a.tar.bz2 |
#1286: allow using fileinput.FileInput as context manager.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/fileinput.py | 6 | ||||
-rw-r--r-- | Lib/test/test_fileinput.py | 24 |
2 files changed, 30 insertions, 0 deletions
diff --git a/Lib/fileinput.py b/Lib/fileinput.py index 90a600b..a25a021 100644 --- a/Lib/fileinput.py +++ b/Lib/fileinput.py @@ -238,6 +238,12 @@ class FileInput: self.nextfile() self._files = () + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + def __iter__(self): return self diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py index aae16ea..f312882 100644 --- a/Lib/test/test_fileinput.py +++ b/Lib/test/test_fileinput.py @@ -231,6 +231,30 @@ class FileInputTests(unittest.TestCase): ## finally: ## remove_tempfiles(t1) + def test_context_manager(self): + try: + t1 = writeTmp(1, ["A\nB\nC"]) + t2 = writeTmp(2, ["D\nE\nF"]) + with FileInput(files=(t1, t2)) as fi: + lines = list(fi) + self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"]) + self.assertEqual(fi.filelineno(), 3) + self.assertEqual(fi.lineno(), 6) + self.assertEqual(fi._files, ()) + finally: + remove_tempfiles(t1, t2) + + def test_close_on_exception(self): + try: + t1 = writeTmp(1, [""]) + with FileInput(files=t1) as fi: + raise IOError + except IOError: + self.assertEqual(fi._files, ()) + finally: + remove_tempfiles(t1) + + def test_main(): run_unittest(BufferSizesTests, FileInputTests) |