Skip to content

Fix possible dataloss during finalization with GzipFile #159422

Open

Description

@brittanyrey

Bug report

After stumbling into #159419, which addresses possible dataloss during finalization. I decided to take a quick pass across some of our other writers to see if the same bug exists elsewhere. I came across this issue in GzipFile, where trying to import a module at finalization could trigger an ImportError that results in the file never being properly closed.

current implementation

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

    super().__del__()  # then, this line will never run

example

import gzip
f = gzip.open("out.gz", "wb")
f.write(b"important data\n" * 1000)
# never explicitly closed; finalized at shutdown
$ python repro.py
Exception ignored while calling deallocator <function GzipFile.__del__ ...>:
ImportError: sys.meta_path is None, Python is likely shutting down

CPython versions tested on:

3.14, 3.15, 3.16

Operating systems tested on:

No response

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions