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.
This commit is contained in:
Victor Stinner 2022-06-13 19:24:00 +02:00 committed by GitHub
parent 3ceb4b8d3a
commit 443ca731d6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 2 deletions

View 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