Index: Doc/library/tarfile.rst =================================================================== --- Doc/library/tarfile.rst (revision 78438) +++ Doc/library/tarfile.rst (working copy) @@ -676,7 +676,14 @@ tar.add("foo", filter=reset) tar.close() +How to use :func:`tarfile.open` as a context manager +(see :ref:`typecontextmanager`):: + import tarfile + with tarfile.open("sample.tar.gz", "w") as tar: + for file in ("file1", "file2"): + tar.add(file) + .. _tar-formats: Supported tar formats @@ -756,4 +763,3 @@ representation. This is the default scheme. In write mode the default value for *errors* is ``'strict'`` to ensure that name information is not altered unnoticed. - Index: Lib/tarfile.py =================================================================== --- Lib/tarfile.py (revision 78438) +++ 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 78438) +++ Lib/test/test_tarfile.py (working copy) @@ -327,7 +327,23 @@ 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) + self.assertTrue(tar.closed) + def test_context_manager_exception(self): + try: + # tarfile can be used as a context manager + with tarfile.open(tarname) as tar: + self.assertFalse(tar.closed) + raise Exception + except: + self.assertTrue(tar.closed) + else: + self.fail("Exception not reraised.") + class StreamReadTest(CommonReadTest): mode="r|"