Skip to content

Commit 328dbc0

Browse files
authored
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.
1 parent 7173fd5 commit 328dbc0

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

Lib/argparse.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@
8484
'ZERO_OR_MORE',
8585
]
8686

87-
87+
import atexit as _atexit
8888
import os as _os
8989
import re as _re
9090
import sys as _sys
@@ -1268,8 +1268,12 @@ def __call__(self, string):
12681268

12691269
# all other arguments are used as file names
12701270
try:
1271-
return open(string, self._mode, self._bufsize, self._encoding,
1272-
self._errors)
1271+
fh = open(string, self._mode, self._bufsize, self._encoding, self._errors)
1272+
1273+
# Register cleanup function to close file
1274+
_atexit.register(fh.close)
1275+
1276+
return fh
12731277
except OSError as e:
12741278
args = {'filename': string, 'error': e}
12751279
message = _("can't open '%(filename)s': %(error)s")

Misc/ACKS

+1
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ Nicolas Chauvat
313313
Jerry Chen
314314
Michael Chermside
315315
Ingrid Cheung
316+
Adam Chhina
316317
Terry Chia
317318
Albert Chin-A-Young
318319
Adal Chiriliuc
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
FileType objects from argparse may not be closed and lead to
2+
ResourceWarning. Register a file.close function with atexit for FileType
3+
objects to ensure they are closed. Patch Contributed by Adam Chhina.

0 commit comments

Comments
 (0)