]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-93353: Fix importlib.resources._tempfile() finalizer (#93377)
authorVictor Stinner <vstinner@python.org>
Mon, 13 Jun 2022 17:24:00 +0000 (19:24 +0200)
committerGitHub <noreply@github.com>
Mon, 13 Jun 2022 17:24:00 +0000 (19:24 +0200)
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.

Lib/importlib/resources/_common.py
Misc/NEWS.d/next/Library/2022-05-31-14-58-40.gh-issue-93353.9Hvm6o.rst [new file with mode: 0644]

index 147ea19188f718e4dc7d40f0fec6918e9af77e1a..ca1fa8ab2fe6ff28313134ef37d7c71676280b35 100644 (file)
@@ -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 (file)
index 0000000..67be3c6
--- /dev/null
@@ -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.