Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions Lib/gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,12 +467,13 @@ def readline(self, size=-1):
return self._buffer.readline(size)

def __del__(self):
if self.mode == WRITE and not self.closed:
import warnings
warnings.warn("unclosed GzipFile",
ResourceWarning, source=self, stacklevel=2)

super().__del__()
try:
if self.mode == WRITE and not self.closed:
import warnings
warnings.warn("unclosed GzipFile",
ResourceWarning, source=self, stacklevel=2)
finally:
super().__del__()

def _read_exact(fp, n):
'''Read exactly *n* bytes from `fp`
Expand Down
15 changes: 14 additions & 1 deletion Lib/test/test_gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import unittest
from subprocess import PIPE, Popen
from unittest import mock
from test.support import catch_unraisable_exception
from test.support import catch_unraisable_exception, gc_collect
from test.support import force_not_colorized_test_class, import_helper
from test.support import os_helper
from test.support import _4G, bigmemtest, requires_subprocess
Expand Down Expand Up @@ -965,6 +965,19 @@ def test_refloop_unraisable(self):
gc.collect()
self.assertIsNone(cm.unraisable)

def test_del_closes_if_warning_fails(self):
# The file must still be closed if emitting the ResourceWarning
# raises, as can happen at interpreter shutdown.
b = io.BytesIO()
f = gzip.GzipFile(fileobj=b, mode="wb")
f.write(data1)
with (mock.patch("warnings.warn", side_effect=RuntimeError),
catch_unraisable_exception() as cm):
del f
gc_collect()
self.assertIs(cm.unraisable.exc_type, RuntimeError)
self.assertEqual(gzip.decompress(b.getvalue()), data1)


class TestOpen(BaseTest):
def test_binary_modes(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix truncated output when a writable :class:`gzip.GzipFile` that was never
closed is finalized and emitting its :exc:`ResourceWarning` fails, for
example at interpreter shutdown. The file is now always closed.
Loading