[Python-checkins] gh-93353: Fix importlib.resources._tempfile() finalizer (GH-93377)

miss-islington webhook-mailer at python.org
Mon Jun 13 13:49:59 EDT 2022


https://github.com/python/cpython/commit/dc6dd8ee873ed96027d30c8a2e96518657d46241
commit: dc6dd8ee873ed96027d30c8a2e96518657d46241
branch: 3.11
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2022-06-13T10:49:48-07:00
summary:

gh-93353: Fix importlib.resources._tempfile() finalizer (GH-93377)


Fix the importlib.resources.as_file() context manager to remove the
temporary file if destroyed late during Python finalization: keep a
local reference to the os.remove() function. Patch by Victor Stinner.
(cherry picked from commit 443ca731d6b1267fe2f92985e0490460c95e44a8)

Co-authored-by: Victor Stinner <vstinner at python.org>

files:
A Misc/NEWS.d/next/Library/2022-05-31-14-58-40.gh-issue-93353.9Hvm6o.rst
M Lib/importlib/resources/_common.py

diff --git a/Lib/importlib/resources/_common.py b/Lib/importlib/resources/_common.py
index 147ea19188f71..ca1fa8ab2fe6f 100644
--- a/Lib/importlib/resources/_common.py
+++ b/Lib/importlib/resources/_common.py
@@ -67,7 +67,10 @@ def from_package(package):
 
 
 @contextlib.contextmanager
-def _tempfile(reader, suffix=''):
+def _tempfile(reader, suffix='',
+              # gh-93353: Keep a reference to call os.remove() in late Python
+              # finalization.
+              *, _os_remove=os.remove):
     # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
     # blocks due to the need to close the temporary file to work on Windows
     # properly.
@@ -81,7 +84,7 @@ def _tempfile(reader, suffix=''):
         yield pathlib.Path(raw_path)
     finally:
         try:
-            os.remove(raw_path)
+            _os_remove(raw_path)
         except FileNotFoundError:
             pass
 
diff --git a/Misc/NEWS.d/next/Library/2022-05-31-14-58-40.gh-issue-93353.9Hvm6o.rst b/Misc/NEWS.d/next/Library/2022-05-31-14-58-40.gh-issue-93353.9Hvm6o.rst
new file mode 100644
index 0000000000000..67be3c68f47cb
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-05-31-14-58-40.gh-issue-93353.9Hvm6o.rst
@@ -0,0 +1,3 @@
+Fix the :func:`importlib.resources.as_file` context manager to remove the
+temporary file if destroyed late during Python finalization: keep a local
+reference to the :func:`os.remove` function. Patch by Victor Stinner.



More information about the Python-checkins mailing list