Skip to content

Commit

Permalink
pythongh-58032: Deprecate the argparse.FileType type converter
Browse files Browse the repository at this point in the history
  • Loading branch information
serhiy-storchaka committed Sep 27, 2024
1 parent 3a0e7f5 commit 8527cfa
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 22 deletions.
34 changes: 17 additions & 17 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ help_ Help message for an argument
metavar_ Alternate display name for the argument as shown in help
nargs_ Number of times the argument can be used :class:`int`, ``'?'``, ``'*'``, or ``'+'``
required_ Indicate whether an argument is required or optional ``True`` or ``False``
:ref:`type <argparse-type>` Automatically convert an argument to the given type :class:`int`, :class:`float`, ``argparse.FileType('w')``, or callable function
:ref:`type <argparse-type>` Automatically convert an argument to the given type :class:`int`, :class:`float`, or callable function
============================ =========================================================== ==========================================================================================================================


Expand Down Expand Up @@ -1022,16 +1022,14 @@ See also :ref:`specifying-ambiguous-arguments`. The supported values are:
output files::

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
... default=sys.stdin)
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
... default=sys.stdout)
>>> parser.add_argument('infile', nargs='?')
>>> parser.add_argument('outfile', nargs='?')
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Namespace(infile='input.txt', outfile='output.txt')
>>> parser.parse_args(['input.txt'])
Namespace(infile='input.txt', outfile=None)
>>> parser.parse_args([])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Namespace(infile=None, outfile=None)

.. index:: single: * (asterisk); in argparse module

Expand Down Expand Up @@ -1188,8 +1186,6 @@ Common built-in types and functions can be used as type converters:
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
parser.add_argument('datapath', type=pathlib.Path)

User defined functions can be used as well:
Expand Down Expand Up @@ -1218,12 +1214,6 @@ better reporting than can be given by the ``type`` keyword. A
:exc:`~json.JSONDecodeError` would not be well formatted and a
:exc:`FileNotFoundError` exception would not be handled at all.

Even :class:`~argparse.FileType` has its limitations for use with the ``type``
keyword. If one argument uses *FileType* and then a subsequent argument fails,
an error is reported but the file is not automatically closed. In this case, it
would be better to wait until after the parser has run and then use the
:keyword:`with`-statement to manage the files.

For type checkers that simply check against a fixed set of values, consider
using the choices_ keyword instead.

Expand Down Expand Up @@ -2004,9 +1994,19 @@ FileType objects
>>> parser.parse_args(['-'])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)

.. note::

If one argument uses *FileType* and then a subsequent argument fails,
an error is reported but the file is not automatically closed.
This can also clobber the output files.
In this case, it would be better to wait until after the parser has
run and then use the :keyword:`with`-statement to manage the files.

.. versionchanged:: 3.4
Added the *encodings* and *errors* parameters.

.. deprecated:: 3.14


Argument groups
^^^^^^^^^^^^^^^
Expand Down
6 changes: 6 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,12 @@ Deprecated
as a single positional argument.
(Contributed by Serhiy Storchaka in :gh:`109218`.)

* :mod:`argparse`:
Deprecated the :class:`argparse.FileType` type converter.
Anything with resource management should be done downstream after the
arguments are parsed.
(Contributed by Serhiy Storchaka in :gh:`58032`.)

* :mod:`multiprocessing` and :mod:`concurrent.futures`:
The default start method (see :ref:`multiprocessing-start-methods`) changed
away from *fork* to *forkserver* on platforms where it was not already
Expand Down
11 changes: 6 additions & 5 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@
'integers', metavar='int', nargs='+', type=int,
help='an integer to be summed')
parser.add_argument(
'--log', default=sys.stdout, type=argparse.FileType('w'),
'--log',
help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()
with (open(args.log, 'w') if args.log is not None
else contextlib.nullcontext(sys.stdout)) as log:
log.write('%s' % sum(args.integers))
The module contains the following public classes:
Expand All @@ -39,7 +40,7 @@
- FileType -- A factory for defining types of files to be created. As the
example above shows, instances of FileType are typically passed as
the type= argument of add_argument() calls.
the type= argument of add_argument() calls. Deprecated.
- Action -- The base class for parser actions. Typically actions are
selected by passing strings like 'store_true' or 'append_const' to
Expand Down Expand Up @@ -1239,7 +1240,7 @@ def __call__(self, parser, namespace, values, option_string=None):
# ==============

class FileType(object):
"""Factory for creating file object types
"""Deprecated factory for creating file object types
Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Deprecate the :class:`argparse.FileType` type converter.

0 comments on commit 8527cfa

Please sign in to comment.