From 36001422759839c001d14b1651ad1504bb388b57 Mon Sep 17 00:00:00 2001 From: Aman Date: Sat, 2 Apr 2022 14:53:06 -0400 Subject: [PATCH 1/2] bpo-41395: Register a cleanup function to close files for FileType objects in argparse --- Lib/argparse.py | 8 +++++++- Misc/ACKS | 1 + .../next/Library/2022-04-02-14-40-53.bpo-41395.Y1ZVvT.rst | 3 +++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2022-04-02-14-40-53.bpo-41395.Y1ZVvT.rst diff --git a/Lib/argparse.py b/Lib/argparse.py index 429a72ab7841e7..4d41104075aa80 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -1268,8 +1268,14 @@ def __call__(self, string): # all other arguments are used as file names try: - return open(string, self._mode, self._bufsize, self._encoding, + file = open(string, self._mode, self._bufsize, self._encoding, self._errors) + + # Register cleanup function to close file + import atexit + atexit.register(file.close) + + return file 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 df851bb834cd4e..4646d88dae554e 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -312,6 +312,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 00000000000000..5358b0e71715e2 --- /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. From a47430fff73363b0f21cc0d437eac738562c7643 Mon Sep 17 00:00:00 2001 From: Aman Date: Thu, 14 Apr 2022 10:02:17 -0400 Subject: [PATCH 2/2] Added import as top level import, and renamed file as fh. --- Lib/argparse.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Lib/argparse.py b/Lib/argparse.py index 4d41104075aa80..881dfda6d4d932 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,14 +1268,12 @@ def __call__(self, string): # all other arguments are used as file names try: - file = 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 - import atexit - atexit.register(file.close) + _atexit.register(fh.close) - return file + return fh except OSError as e: args = {'filename': string, 'error': e} message = _("can't open '%(filename)s': %(error)s")