diff --git a/Doc/library/gzip.rst b/Doc/library/gzip.rst index 8850a33f4ab..3349a94446d 100644 --- a/Doc/library/gzip.rst +++ b/Doc/library/gzip.rst @@ -59,6 +59,14 @@ The module defines the following items: .. versionchanged:: 3.6 Accepts a :term:`path-like object`. +.. exception:: BadGzipFile + + An exception raised for invalid gzip files. It inherits :exc:`OSError`. + :exc:`EOFError` and :exc:`zlib.error` can also be raised for invalid gzip + files. + + .. versionadded:: 3.8 + .. class:: GzipFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None) Constructor for the :class:`GzipFile` class, which simulates most of the diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst index 2cfb110b3d5..684656fc2a5 100644 --- a/Doc/whatsnew/3.8.rst +++ b/Doc/whatsnew/3.8.rst @@ -304,6 +304,11 @@ gzip Added the *mtime* parameter to :func:`gzip.compress` for reproducible output. (Contributed by Guo Ci Teo in :issue:`34898`.) +A :exc:`~gzip.BadGzipFile` exception is now raised instead of :exc:`OSError` +for certain types of invalid or corrupt gzip files. +(Contributed by Filip Gruszczyński, Michele Orrù, and Zackery Spytz in +:issue:`6584`.) + idlelib and IDLE ---------------- diff --git a/Lib/gzip.py b/Lib/gzip.py index 7c861874198..2968f475efa 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -11,7 +11,7 @@ import builtins import io import _compression -__all__ = ["GzipFile", "open", "compress", "decompress"] +__all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 @@ -112,6 +112,11 @@ class _PaddedFile: def seekable(self): return True # Allows fast-forwarding even in unseekable streams + +class BadGzipFile(OSError): + """Exception raised in some cases for invalid gzip files.""" + + class GzipFile(_compression.BaseStream): """The GzipFile class simulates most of the methods of a file object with the exception of the truncate() method. @@ -413,12 +418,12 @@ class _GzipReader(_compression.DecompressReader): return False if magic != b'\037\213': - raise OSError('Not a gzipped file (%r)' % magic) + raise BadGzipFile('Not a gzipped file (%r)' % magic) (method, flag, self._last_mtime) = struct.unpack("