[New-bugs-announce] [issue13824] argparse.FileType opens a file without excepting resposibility for closing it
report at bugs.python.org
Thu Jan 19 13:25:39 CET 2012
New submission from David Layton <dmlayton at gmail.com>:
argparse.FileType.__call__ opens the specified file and returns it. This is well documented as an anit-idiom in http://docs.python.org/howto/doanddont.html#exceptions.
"...a serious problem — due to implementation details in CPython, the file would not be closed when an exception is raised until the exception handler finishes; and, worse, in other implementations (e.g., Jython) it might not be closed at all regardless of whether or not an exception is raised."
Disregarding the above, handling a file which may or may not have been opened depending the users input requires a bit of boilerplate code compared to the usual with-open idiom.
Additionally, there is no way to prevent FileType from clobbering an existing file when used with write mode.
Given these issues and others, it seems to me that the usefulness of FileType is outweighed by propensity to encourage bad coding. Perhaps, it would be best if FileType (or some replacement) simply checked that the file exists (when such a check is appropriate), it can be opened in the specified mode, and, curry the call to open (i.e. return lambda: open(string, self._mode, self._bufsize))
components: Library (Lib)
nosy: David.Layton, Paolo.Elvati, Stefan.Pfeiffer, bethard, manveru
title: argparse.FileType opens a file without excepting resposibility for closing it
versions: Python 2.7
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce