gh-83648: Support deprecation of options, arguments and subcommands in argparse (GH-114086)

This commit is contained in:
Serhiy Storchaka 2024-02-06 00:41:34 +02:00 committed by GitHub
parent c32bae5290
commit bb57ffdb38
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 262 additions and 27 deletions

View file

@ -777,6 +777,8 @@ The add_argument() method
* dest_ - The name of the attribute to be added to the object returned by
:meth:`parse_args`.
* deprecated_ - Whether or not use of the argument is deprecated.
The following sections describe how each of these are used.
@ -1439,6 +1441,34 @@ behavior::
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
.. _deprecated:
deprecated
^^^^^^^^^^
During a project's lifetime, some arguments may need to be removed from the
command line. Before removing them, you should inform
your users that the arguments are deprecated and will be removed.
The ``deprecated`` keyword argument of
:meth:`~ArgumentParser.add_argument`, which defaults to ``False``,
specifies if the argument is deprecated and will be removed
in the future.
For arguments, if ``deprecated`` is ``True``, then a warning will be
printed to standard error when the argument is used::
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='snake.py')
>>> parser.add_argument('--legs', default=0, type=int, deprecated=True)
>>> parser.parse_args([])
Namespace(legs=0)
>>> parser.parse_args(['--legs', '4']) # doctest: +SKIP
snake.py: warning: option '--legs' is deprecated
Namespace(legs=4)
.. versionchanged:: 3.13
Action classes
^^^^^^^^^^^^^^
@ -1842,7 +1872,8 @@ Sub-commands
{foo,bar} additional help
Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
Furthermore, :meth:`~_SubParsersAction.add_parser` supports an additional
*aliases* argument,
which allows multiple strings to refer to the same subparser. This example,
like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
@ -1853,6 +1884,20 @@ Sub-commands
>>> parser.parse_args(['co', 'bar'])
Namespace(foo='bar')
:meth:`~_SubParsersAction.add_parser` supports also an additional
*deprecated* argument, which allows to deprecate the subparser.
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='chicken.py')
>>> subparsers = parser.add_subparsers()
>>> run = subparsers.add_parser('run')
>>> fly = subparsers.add_parser('fly', deprecated=True)
>>> parser.parse_args(['fly']) # doctest: +SKIP
chicken.py: warning: command 'fly' is deprecated
Namespace()
.. versionadded:: 3.13
One particularly effective way of handling sub-commands is to combine the use
of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
that each subparser knows which Python function it should execute. For