Index: Lib/test/test_tarfile.py =================================================================== --- Lib/test/test_tarfile.py (revision 78212) +++ Lib/test/test_tarfile.py (working copy) @@ -327,7 +327,13 @@ 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) + class StreamReadTest(CommonReadTest): mode="r|" Index: Lib/tarfile.py =================================================================== --- Lib/tarfile.py (revision 78212) +++ Lib/tarfile.py (working copy) @@ -2411,6 +2411,12 @@ """ if level <= self.debug: print >> sys.stderr, msg + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() # class TarFile class TarIter: Index: Doc/library/tarfile.rst =================================================================== --- Doc/library/tarfile.rst (revision 78212) +++ Doc/library/tarfile.rst (working copy) @@ -676,7 +676,13 @@ tar.add("foo", filter=reset) tar.close() +How to use :func:`tarfile.open` as a context manaager:: + 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 +762,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. -