Skip to content

gh-85567: Register a cleanup function to close files for FileType objects in argparse #32257

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
Apr 18, 2022
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
10 changes: 7 additions & 3 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
'ZERO_OR_MORE',
]


import atexit as _atexit
import os as _os
import re as _re
import sys as _sys
Expand Down Expand Up @@ -1268,8 +1268,12 @@ def __call__(self, string):

# all other arguments are used as file names
try:
return open(string, self._mode, self._bufsize, self._encoding,
self._errors)
fh = open(string, self._mode, self._bufsize, self._encoding, self._errors)

# Register cleanup function to close file
_atexit.register(fh.close)

return fh
except OSError as e:
args = {'filename': string, 'error': e}
message = _("can't open '%(filename)s': %(error)s")
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ Nicolas Chauvat
Jerry Chen
Michael Chermside
Ingrid Cheung
Adam Chhina
Terry Chia
Albert Chin-A-Young
Adal Chiriliuc
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FileType objects from argparse may not be closed and lead to
ResourceWarning. Register a file.close function with atexit for FileType
objects to ensure they are closed. Patch Contributed by Adam Chhina.