[Python-checkins] gh-85567: Register a cleanup function to close files for FileType objects in argparse (#32257)
facundobatista
webhook-mailer at python.org
Sun Apr 17 21:53:55 EDT 2022
https://github.com/python/cpython/commit/328dbc051f84bd5fdf61101bb4fa61d85f8b7feb
commit: 328dbc051f84bd5fdf61101bb4fa61d85f8b7feb
branch: main
author: achhina <amanschhina at gmail.com>
committer: facundobatista <facundo at taniquetil.com.ar>
date: 2022-04-17T22:53:37-03:00
summary:
gh-85567: Register a cleanup function to close files for FileType objects in argparse (#32257)
* bpo-41395: Register a cleanup function to close files for FileType objects in argparse
* Added import as top level import, and renamed file as fh.
files:
A Misc/NEWS.d/next/Library/2022-04-02-14-40-53.bpo-41395.Y1ZVvT.rst
M Lib/argparse.py
M Misc/ACKS
diff --git a/Lib/argparse.py b/Lib/argparse.py
index 429a72ab7841e..881dfda6d4d93 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -84,7 +84,7 @@
'ZERO_OR_MORE',
]
-
+import atexit as _atexit
import os as _os
import re as _re
import sys as _sys
@@ -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")
diff --git a/Misc/ACKS b/Misc/ACKS
index 5e66a2e757adf..a1df84c0d6779 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -313,6 +313,7 @@ Nicolas Chauvat
Jerry Chen
Michael Chermside
Ingrid Cheung
+Adam Chhina
Terry Chia
Albert Chin-A-Young
Adal Chiriliuc
diff --git a/Misc/NEWS.d/next/Library/2022-04-02-14-40-53.bpo-41395.Y1ZVvT.rst b/Misc/NEWS.d/next/Library/2022-04-02-14-40-53.bpo-41395.Y1ZVvT.rst
new file mode 100644
index 0000000000000..5358b0e71715e
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-04-02-14-40-53.bpo-41395.Y1ZVvT.rst
@@ -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.
More information about the Python-checkins
mailing list