aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Lib/importlib/resources/_common.py
diff options
context:
space:
mode:
authorVictor Stinner <vstinner@python.org>2022-06-13 19:24:00 +0200
committerGitHub <noreply@github.com>2022-06-13 19:24:00 +0200
commit443ca731d6b1267fe2f92985e0490460c95e44a8 (patch)
tree69e0a0ff3e4d33bcd88dd37ed5947c19b2a630f5 /Lib/importlib/resources/_common.py
parent3ceb4b8d3ad48101e67da8fb8f581d3377863bfa (diff)
downloadcpython-443ca731d6b1267fe2f92985e0490460c95e44a8.tar.gz
cpython-443ca731d6b1267fe2f92985e0490460c95e44a8.zip
gh-93353: Fix importlib.resources._tempfile() finalizer (#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.
Diffstat (limited to 'Lib/importlib/resources/_common.py')
-rw-r--r--Lib/importlib/resources/_common.py7
1 files changed, 5 insertions, 2 deletions
diff --git a/Lib/importlib/resources/_common.py b/Lib/importlib/resources/_common.py
index 147ea19188f..ca1fa8ab2fe 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