diff --git a/Lib/tarfile.py b/Lib/tarfile.py --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -53,6 +53,21 @@ try: except ImportError: grp = pwd = None +try: + import zlib +except ImportError: + zlib = None + +try: + import lzma +except ImportError: + lzma = None + +try: + import bz2 +except ImportError: + bz2 = None + # os.symlink on Windows prior to 6.0 raises NotImplementedError symlink_exception = (AttributeError, NotImplementedError) try: @@ -63,7 +78,7 @@ except NameError: pass # from tarfile import * -__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"] +__all__ = ["TarFile", "TarInfo", "is_tarfile", "formats", "TarError"] from builtins import open as _open # Since 'open' is TarFile.open @@ -413,11 +428,8 @@ class _Stream: try: if comptype == "gz": - try: - import zlib - except ImportError: + if zlib is None: raise CompressionError("zlib module is not available") - self.zlib = zlib self.crc = zlib.crc32(b"") if mode == "r": self._init_read_gz() @@ -426,9 +438,7 @@ class _Stream: self._init_write_gz() elif comptype == "bz2": - try: - import bz2 - except ImportError: + if bz2 is None: raise CompressionError("bz2 module is not available") if mode == "r": self.dbuf = b"" @@ -438,9 +448,7 @@ class _Stream: self.cmp = bz2.BZ2Compressor() elif comptype == "xz": - try: - import lzma - except ImportError: + if lzma is None: raise CompressionError("lzma module is not available") if mode == "r": self.dbuf = b"" @@ -465,10 +473,10 @@ class _Stream: def _init_write_gz(self): """Initialize for writing with gzip compression. """ - self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, - -self.zlib.MAX_WBITS, - self.zlib.DEF_MEM_LEVEL, - 0) + self.cmp = zlib.compressobj(9, zlib.DEFLATED, + -zlib.MAX_WBITS, + zlib.DEF_MEM_LEVEL, + 0) timestamp = struct.pack(" 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'.") - try: - import bz2 - except ImportError: + if bz2 is None: raise CompressionError("bz2 module is not available") fileobj = bz2.BZ2File(filename=name if fileobj is None else None, @@ -1814,9 +1820,7 @@ class TarFile(object): if mode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'") - try: - import lzma - except ImportError: + if lzma is None: raise CompressionError("lzma module is not available") fileobj = lzma.LZMAFile(filename=name if fileobj is None else None, @@ -2559,9 +2563,9 @@ class TarIter: self.index += 1 return tarinfo -#-------------------- -# exported functions -#-------------------- +#--------------------------------- +# exported functions and constants +#--------------------------------- def is_tarfile(name): """Return True if name points to a tar archive that we are able to handle, else return False. @@ -2575,3 +2579,7 @@ def is_tarfile(name): bltn_open = open open = TarFile.open + +formats = [name + for (name, module) in [("gz", zlib), ("xz", lzma), ("bz2", bz2)] + if module is not None]