Index: Doc/library/tarfile.rst =================================================================== --- Doc/library/tarfile.rst (revision 78508) +++ Doc/library/tarfile.rst (working copy) @@ -650,6 +650,14 @@ tar.add(name) tar.close() +The same example using :func:`tarfile.open` as a context manager +(see :ref:`typecontextmanager`):: + + import tarfile + with tarfile.open("sample.tar", "w") as tar: + for name in ["foo", "bar", "quux"]: + tar.add(name) + How to read a gzip compressed tar archive and display some member information:: import tarfile Index: Lib/tarfile.py =================================================================== --- Lib/tarfile.py (revision 78508) +++ Lib/tarfile.py (working copy) @@ -2411,6 +2411,16 @@ """ if level <= self.debug: print >> sys.stderr, msg + + def __enter__(self): + """Enter the runtime context. + """ + return self + + def __exit__(self, type, value, traceback): + """Exit the runtime context without supressing any exceptions. + """ + self.close() # class TarFile class TarIter: Index: Lib/test/test_tarfile.py =================================================================== --- Lib/test/test_tarfile.py (revision 78508) +++ Lib/test/test_tarfile.py (working copy) @@ -327,7 +327,21 @@ finally: os.remove(empty) + def test_context_manager(self): + # TarFile can be used as a context manager. + with tarfile.open(tarname) as tar: + self.assertFalse(tar.closed, "closed inside runtime context") + self.assertTrue(tar.closed, "context manager failed") + def test_context_manager_exception(self): + with self.assertRaises(Exception) as exc: + with tarfile.open(tarname) as tar: + raise IOError + self.assertIsInstance(exc.exception, IOError, + "wrong exception raised in context manager") + self.assertTrue(tar.closed, "context manager failed") + + class StreamReadTest(CommonReadTest): mode="r|"