diff --git a/Lib/gzip.py b/Lib/gzip.py index 247efc01527bb14..88d9157fea3209e 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -11,6 +11,7 @@ import struct import sys import time +import warnings # must stay eager to support finalization import weakref import zlib from compression._common import _streams @@ -229,7 +230,6 @@ def __init__(self, filename=None, mode=None, elif mode.startswith(('w', 'a', 'x')): if origmode is None: - import warnings warnings.warn( "GzipFile was opened for writing, but this will " "change in future Python releases. " @@ -468,7 +468,6 @@ def readline(self, size=-1): def __del__(self): if self.mode == WRITE and not self.closed: - import warnings warnings.warn("unclosed GzipFile", ResourceWarning, source=self, stacklevel=2) diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py index 8bc8e507683cb50..5473f18b57fc1c9 100644 --- a/Lib/test/test_gzip.py +++ b/Lib/test/test_gzip.py @@ -965,6 +965,17 @@ def test_refloop_unraisable(self): gc.collect() self.assertIsNone(cm.unraisable) + @requires_subprocess() + def test_unclosed_at_shutdown(self): + rc, out, err = assert_python_ok("-c", f"""if 1: + import gzip + f = gzip.GzipFile({self.filename!r}, "wb") + f.write({data1!r}) + """) + self.assertNotIn(b"Exception ignored", err) + with gzip.GzipFile(self.filename) as f: + self.assertEqual(f.read(), data1) + class TestOpen(BaseTest): def test_binary_modes(self): diff --git a/Misc/NEWS.d/next/Library/2026-10-14-15-50-59.gh-issue-159422.16mSqQ.rst b/Misc/NEWS.d/next/Library/2026-10-14-15-50-59.gh-issue-159422.16mSqQ.rst new file mode 100644 index 000000000000000..9250b8f0036c3f8 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-14-15-50-59.gh-issue-159422.16mSqQ.rst @@ -0,0 +1,4 @@ +:mod:`gzip` now imports :mod:`warnings` eagerly so that a writable +:class:`~gzip.GzipFile` left unclosed at interpreter shutdown can emit its +:exc:`ResourceWarning` and be closed instead of failing with an +:exc:`ImportError`.