Index: Doc/library/tarfile.rst =================================================================== --- Doc/library/tarfile.rst (revision 78514) +++ Doc/library/tarfile.rst (working copy) @@ -234,7 +234,12 @@ archive several times. Each archive member is represented by a :class:`TarInfo` object, see :ref:`tarinfo-objects` for details. +A :class:`TarFile` object can be used as a context manager in a :keyword:`with` +statement. See the :ref:`tar-examples` section for a use case. +.. versionadded:: 2.7 + + .. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors=None, pax_headers=None, debug=0, errorlevel=0) All following arguments are optional and can be accessed as instance attributes @@ -650,6 +655,14 @@ tar.add(name) tar.close() +The same example using the :keyword:`with` statement. This guarantees that the +:class:`TarFile` object will be finally closed even in case of an error:: + + 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 78514) +++ Lib/tarfile.py (working copy) @@ -2411,6 +2411,13 @@ """ if level <= self.debug: print >> sys.stderr, msg + + def __enter__(self): + self._check() + return self + + def __exit__(self, type, value, traceback): + self.close() # class TarFile class TarIter: Index: Lib/test/test_tarfile.py =================================================================== --- Lib/test/test_tarfile.py (revision 78514) +++ Lib/test/test_tarfile.py (working copy) @@ -327,7 +327,27 @@ finally: os.remove(empty) + def test_context_manager(self): + 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_closed(self): + tar = tarfile.open(tarname) + tar.close() + with self.assertRaises(IOError): + with tar: + pass + + 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|"