Skip to content

Avoid file descriptor refleaks in as_file. #234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
v5.2.2
======

* #234: Fix refleak in ``as_file`` caught by CPython tests.

v5.2.1
======

Expand Down
8 changes: 5 additions & 3 deletions importlib_resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,16 @@ def _tempfile(reader, suffix=''):
# properly.
fd, raw_path = tempfile.mkstemp(suffix=suffix)
try:
os.write(fd, reader())
os.close(fd)
try:
os.write(fd, reader())
finally:
os.close(fd)
del reader
yield pathlib.Path(raw_path)
finally:
try:
os.remove(raw_path)
except (FileNotFoundError, PermissionError):
except FileNotFoundError:
Copy link
Member

@FFY00 FFY00 Jul 31, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this part though? IIRC it was added because for some reason Windows will set high permissions on temporary files sometimes.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this exception was masking the underlying issue that the file descriptor wasn't being closed. Windows won't allow deletion of files in use, so when we encountered the issue, we suppressed the exception, allowing the file descriptor to remain unclosed and on Windows leaving the file undeleted. Now that the file descriptor is unconditionally closed, there's no longer any need to suppress this exception and as you can see, tests still pass on Windows.

pass


Expand Down