Skip to content

gh-81954: Eagerly import warnings module to failure of ZipFile.__del__ during finalization - #159419

Open
brittanyrey wants to merge 4 commits into
python:mainfrom
brittanyrey:b-zipfile-del-close
Open

brittanyrey wants to merge 4 commits into
python:mainfrom
brittanyrey:b-zipfile-del-close

Conversation

@brittanyrey

@brittanyrey brittanyrey commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

BUG: Now that ZipFile delivers ResourceWarnings during __del__ calls, if there was an issue lazily loading warnings during finalization, the close() call was missed entirely. This left the file in an unexpected state and introduced a possibility of data loss that didn't exist previously.

FIX: Eager import warnings

ZipFile.__del__ emitted its ResourceWarning before calling close().
When warnings.warn() raised, close() was skipped and the central
directory of a writable archive was never written, leaving a corrupt
file. This happens at interpreter shutdown, where resolving the lazy
"warnings" import raises ImportError, and with -W
error::ResourceWarning at any time.

Call close() in a finally block.

@msullivan msullivan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems good to me

Comment thread Lib/zipfile/__init__.py Outdated
@brittanyrey

Copy link
Copy Markdown
Contributor Author

Thanks for the review Sully @msullivan !

Comment thread Lib/test/test_zipfile/test_core.py Outdated
Comment thread Lib/test/test_zipfile/test_core.py Outdated
Comment thread Misc/NEWS.d/next/Library/2026-10-14-14-47-05.gh-issue-81954.KvM0gY.rst Outdated
Comment thread Lib/test/test_zipfile/test_core.py Outdated
Comment thread Lib/test/test_zipfile/test_core.py Outdated
Comment thread Lib/test/test_zipfile/test_core.py Outdated
@brittanyrey brittanyrey changed the title gh-81954: Always close ZipFile in __del__ even if the warning fails gh-81954: Eagerly import warnings module to failure of ZipFile.__del__ during finalization Oct 15, 2026
@brittanyrey

Copy link
Copy Markdown
Contributor Author

Updated!

@cmaloney cmaloney left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The NEWS is a little bit long but overall looking good. I like the comment about why the import warnings is not lazy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants