Skip to content

Commit f9585e2

Browse files
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 443ca73) Co-authored-by: Victor Stinner <[email protected]>
1 parent 58277de commit f9585e2

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

Lib/importlib/_common.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,10 @@ def from_package(package):
8080

8181

8282
@contextlib.contextmanager
83-
def _tempfile(reader, suffix=''):
83+
def _tempfile(reader, suffix='',
84+
# gh-93353: Keep a reference to call os.remove() in late Python
85+
# finalization.
86+
*, _os_remove=os.remove):
8487
# Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
8588
# blocks due to the need to close the temporary file to work on Windows
8689
# properly.
@@ -92,7 +95,7 @@ def _tempfile(reader, suffix=''):
9295
yield pathlib.Path(raw_path)
9396
finally:
9497
try:
95-
os.remove(raw_path)
98+
_os_remove(raw_path)
9699
except FileNotFoundError:
97100
pass
98101

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix the :func:`importlib.resources.as_file` context manager to remove the
2+
temporary file if destroyed late during Python finalization: keep a local
3+
reference to the :func:`os.remove` function. Patch by Victor Stinner.

0 commit comments

Comments
 (0)