Skip to content

Commit

Permalink
gh-93353: Fix importlib.resources._tempfile() finalizer (GH-93377)
Browse files Browse the repository at this point in the history
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 <vstinner@python.org>
  • Loading branch information
miss-islington and vstinner committed Jun 13, 2022
1 parent 58277de commit f9585e2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
7 changes: 5 additions & 2 deletions Lib/importlib/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,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.
Expand All @@ -92,7 +95,7 @@ def _tempfile(reader, suffix=''):
yield pathlib.Path(raw_path)
finally:
try:
os.remove(raw_path)
_os_remove(raw_path)
except FileNotFoundError:
pass

Expand Down
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit f9585e2

Please sign in to comment.