Index: Lib/tarfile.py =================================================================== --- Lib/tarfile.py (revision 75934) +++ Lib/tarfile.py (working copy) @@ -1579,6 +1579,16 @@ self.fileobj.write(buf) self.offset += len(buf) + #-------------------------------------------------------------------------- + # Support of 'with' statemet + #-------------------------------------------------------------------------- + def __enter__(self): + return self + + def __exit__(self, type, value, tb): + self.close() + + def _getposix(self): return self.format == USTAR_FORMAT def _setposix(self, value): Index: Lib/test/test_tarfile.py =================================================================== --- Lib/test/test_tarfile.py (revision 75934) +++ Lib/test/test_tarfile.py (working copy) @@ -1261,6 +1261,23 @@ def test_partial_input_bz2(self): self._test_partial_input("r:bz2") +class WithStmtTest(unittest.TestCase): + # Support of with statement + tarname = tarname + mode = "r:" + + def test_with_statement (self): + with tarfile.open(self.tarname) as self.tar: + tarinfo = self.tar.getmember("ustar/regtype") + fobj = self.tar.extractfile(tarinfo) + data = fobj.read() + self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype), + "extraction using 'with' statement failed") + + self.assertTrue(self.tar.closed, "file not closed using 'with' statement") + + + def test_main(): if not os.path.exists(TEMPDIR): @@ -1283,6 +1300,7 @@ PaxUnicodeTest, AppendTest, LimitsTest, + WithStmtTest ] if hasattr(os, "link"):