8000 gh-126071: Improve formatting of the argparse documentation (GH-126073) · python/cpython@2ab377a · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 2ab377a

Browse files
gh-126071: Improve formatting of the argparse documentation (GH-126073)
* Use appropriate roles for ArgumentParser, Action, etc. * Remove superfluous repeated links. * Explicitly document signatures and add index entries for some methods and classes. * Make it more clear that some parameters are keyword-only. * Fix some minor errors.
1 parent 00e5ec0 commit 2ab377a

File tree

1 file changed

+72
-65
lines changed

1 file changed

+72
-65
lines changed

Doc/library/argparse.rst

Lines changed: 72 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ the extracted data in a :class:`argparse.Namespace` object::
5050
print(args.filename, args.count, args.verbose)
5151

5252
.. note::
53-
If you're looking a guide about how to upgrade optparse code
54-
to argparse, see :ref:`Upgrading Optparse Code <upgrading-optparse-code>`.
53+
If you're looking for a guide about how to upgrade :mod:`optparse` code
54+
to :mod:`!argparse`, see :ref:`Upgrading Optparse Code <upgrading-optparse-code>`.
5555

5656
ArgumentParser objects
5757
----------------------
@@ -101,7 +101,7 @@ ArgumentParser objects
101101
* allow_abbrev_ - Allows long options to be abbreviated if the
102102
abbreviation is unambiguous. (default: ``True``)
103103

104-
* exit_on_error_ - Determines whether or not ArgumentParser exits with
104+
* exit_on_error_ - Determines whether or not :class:`!ArgumentParser` exits with
105105
error info when an error occurs. (default: ``True``)
106106

107107
* suggest_on_error_ - Enables suggestions for mistyped argument choices
@@ -381,7 +381,7 @@ Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
381381
Parsers that need to support different or additional prefix
382382
characters, e.g. for options
383383
like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
384-
to the ArgumentParser constructor::
384+
to the :class:`ArgumentParser` constructor::
385385

386386
>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
387387
>>> parser.add_argument('+f')
@@ -512,9 +512,9 @@ string was overridden.
512512
add_help
513513
^^^^^^^^
514514

515-
By default, ArgumentParser objects add an option which simply displays
515+
By default, :class:`ArgumentParser` objects add an option which simply displays
516516
the parser's help message. If ``-h`` or ``--help`` is supplied at the command
517-
line, the ArgumentParser help will be printed.
517+
line, the :class:`!ArgumentParser` help will be printed.
518518

519519
Occasionally, it may be useful to disable the addition of this help option.
520520
This can be achieved by passing ``False`` as the ``add_help=`` argument to
@@ -589,15 +589,15 @@ are strings::
589589
The add_argument() method
590590
-------------------------
591591

592-
.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
592+
.. method:: ArgumentParser.add_argument(name or flags..., *, [action], [nargs], \
593593
[const], [default], [type], [choices], [required], \
594594
[help], [metavar], [dest], [deprecated])
595595

596596
Define how a single command-line argument should be parsed. Each parameter
597597
has its own more detailed description below, but in short they are:
598598

599-
* `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
600-
or ``-f, --foo``.
599+
* `name or flags`_ - Either a name or a list of option strings, e.g. ``'foo'``
600+
or ``'-f', '--foo'``.
601601

602602
* action_ - The basic type of action to be taken when this argument is
603603
encountered at the command line.
@@ -662,7 +662,7 @@ be positional::
662662
usage: PROG [-h] [-f FOO] bar
663663
PROG: error: the following arguments are required: bar
664664

665-
By default, argparse automatically handles the internal naming and
665+
By default, :mod:`!argparse` automatically handles the internal naming and
666666
display names of arguments, simplifying the process without requiring
667667
additional configuration.
668668
As such, you do not need to specify the dest_ and metavar_ parameters.
@@ -784,22 +784,24 @@ how the command-line arguments should be handled. The supplied actions are:
784784
Only actions that consume command-line arguments (e.g. ``'store'``,
785785
``'append'`` or ``'extend'``) can be used with positional arguments.
786786

787-
You may also specify an arbitrary action by passing an Action subclass or
788-
other object that implements the same interface. The ``BooleanOptionalAction``
789-
is available in ``argparse`` and adds support for boolean actions such as
790-
``--foo`` and ``--no-foo``::
787+
.. class:: BooleanOptionalAction
791788

792-
>>> import argparse
793-
>>> parser = argparse.ArgumentParser()
794-
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
795-
>>> parser.parse_args(['--no-foo'])
796-
Namespace(foo=False)
789+
You may also specify an arbitrary action by passing an :class:`Action` subclass or
790+
other object that implements the same interface. The :class:`!BooleanOptionalAction`
791+
is available in :mod:`!argparse` and adds support for boolean actions such as
792+
``--foo`` and ``--no-foo``::
797793

798-
.. versionadded:: 3.9
794+
>>> import argparse
795+
>>> parser = argparse.ArgumentParser()
796+
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
797+
>>> parser.parse_args(['--no-foo'])
798+
Namespace(foo=False)
799+
800+
.. versionadded:: 3.9
799801

800802
The recommended way to create a custom action is to extend :class:`Action`,
801-
overriding the ``__call__`` method and optionally the ``__init__`` and
802-
``format_usage`` methods.
803+
overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` and
804+
:meth:`!format_usage` methods.
803805

804806
An example of a custom action::
805807

@@ -829,7 +831,7 @@ For more details, see :class:`Action`.
829831
nargs
830832
^^^^^
831833

832-
ArgumentParser objects usually associate a single command-line argument with a
834+
:class:`ArgumentParser` objects usually associate a single command-line argument with a
833835
single action to be taken. The ``nargs`` keyword argument associates a
834836
different number of command-line arguments with a single action.
835837
See also :ref:`specifying-ambiguous-arguments`. The supported values are:
@@ -1115,7 +1117,7 @@ many choices), just specify an explicit metavar_.
11151117
required
11161118
^^^^^^^^
11171119

1118-
In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
1120+
In general, the :mod:`!argparse` module assumes that flags like ``-f`` and ``--bar``
11191121
indicate *optional* arguments, which can always be omitted at the command line.
11201122
To make an option *required*, ``True`` can be specified for the ``required=``
11211123
keyword argument to :meth:`~ArgumentParser.add_argument`::
@@ -1168,7 +1170,7 @@ specifiers include the program name, ``%(prog)s`` and most keyword arguments to
11681170
As the help string supports %-formatting, if you want a literal ``%`` to appear
11691171
in the help string, you must escape it as ``%%``.
11701172

1171-
:mod:`argparse` supports silencing the help entry for certain options, by
1173+
:mod:`!argparse` supports silencing the help entry for certain options, by
11721174
setting the ``help`` value to ``argparse.SUPPRESS``::
11731175

11741176
>>> parser = argparse.ArgumentParser(prog='frobble')
@@ -1186,7 +1188,7 @@ metavar
11861188
^^^^^^^
11871189

11881190
When :class:`ArgumentParser` generates help messages, it needs some way to refer
1189-
to each expected argument. By default, ArgumentParser objects use the dest_
1191+
to each expected argument. By default, :class:`!ArgumentParser` objects use the dest_
11901192
value as the "name" of each object. By default, for positional argument
11911193
actions, the dest_ value is used directly, and for optional argument actions,
11921194
the dest_ value is uppercased. So, a single positional argument with
@@ -1318,7 +1320,7 @@ printed to :data:`sys.stderr` when the argument is used::
13181320
Action classes
13191321
^^^^^^^^^^^^^^
13201322

1321-
Action classes implement the Action API, a callable which returns a callable
1323+
:class:`!Action` classes implement the Action API, a callable which returns a callable
13221324
which processes arguments from the command-line. Any object which follows
13231325
this API may be passed as the ``action`` parameter to
13241326
:meth:`~ArgumentParser.add_argument`.
@@ -1327,40 +1329,45 @@ this API may be passed as the ``action`` parameter to
13271329
type=None, choices=None, required=False, help=None, \
13281330
metavar=None)
13291331

1330-
Action objects are used by an ArgumentParser to represent the information
1332+
:class:`!Action` objects are used by an :class:`ArgumentParser` to represent the information
13311333
needed to parse a single argument from one or more strings from the
1332-
command line. The Action class must accept the two positional arguments
1334+
command line. The :class:`!Action` class must accept the two positional arguments
13331335
plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
13341336
except for the ``action`` itself.
13351337

1336-
Instances of Action (or return value of any callable to the ``action``
1337-
parameter) should have attributes "dest", "option_strings", "default", "type",
1338-
"required", "help", etc. defined. The easiest way to ensure these attributes
1339-
are defined is to call ``Action.__init__``.
1338+
Instances of :class:`!Action` (or return value of any callable to the
1339+
``action`` parameter) should have attributes :attr:`!dest`,
1340+
:attr:`!option_strings`, :attr:`!default`, :attr:`!type`, :attr:`!required`,
1341+
:attr:`!help`, etc. defined. The easiest way to ensure these attributes
1342+
are defined is to call :meth:`!Action.__init__`.
1343+
1344+
.. method:: __call__(parser, namespace, values, option_string=None)
1345+
1346+
:class:`!Action` instances should be callable, so subclasses must override the
1347+
:meth:`!__call__` method, which should accept four parameters:
13401348

1341-
Action instances should be callable, so subclasses must override the
1342-
``__call__`` method, which should accept four parameters:
1349+
* *parser* - The :class:`ArgumentParser` object which contains this action.
13431350

1344-
* *parser* - The ArgumentParser object which contains this action.
1351+
* *namespace* - The :class:`Namespace` object that will be returned by
1352+
:meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1353+
object using :func:`setattr`.
13451354

1346-
* *namespace* - The :class:`Namespace` object that will be returned by
1347-
:meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1348-
object using :func:`setattr`.
1355+
* *values* - The associated command-line arguments, with any type conversions
1356+
applied. Type conversions are specified with the type_ keyword argument to
1357+
:meth:`~ArgumentParser.add_argument`.
13491358

1350-
* *values* - The associated command-line arguments, with any type conversions
1351-
applied. Type conversions are specified with the type_ keyword argument to
1352-
:meth:`~ArgumentParser.add_argument`.
1359+
* *option_string* - The option string that was used to invoke this action.
1360+
The ``option_string`` argument is optional, and will be absent if the action
1361+
is associated with a positional argument.
13531362

1354-
* *option_string* - The option string that was used to invoke this action.
1355-
The ``option_string`` argument is optional, and will be absent if the action
1356-
is associated with a positional argument.
1363+
The :meth:`!__call__` method may perform arbitrary actions, but will typically set
1364+
attributes on the ``namespace`` based on ``dest`` and ``values``.
13571365

1358-
The ``__call__`` method may perform arbitrary actions, but will typically set
1359-
attributes on the ``namespace`` based on ``dest`` and ``values``.
1366+
.. method:: format_usage()
13601367

1361-
Action subclasses can define a ``format_usage`` method that takes no argument
1362-
and return a string which will be used when printing the usage of the program.
1363-
If such method is not provided, a sensible default will be used.
1368+
:class:`!Action` subclasses can define a :meth:`!format_usage` method that takes no argument
1369+
and return a string which will be used when printing the usage of the program.
1370+
If such method is not provided, a sensible default will be used.
13641371

13651372

13661373
The parse_args() method
@@ -1373,7 +1380,7 @@ The parse_args() method
13731380

13741381
Previous calls to :meth:`add_argument` determine exactly what objects are
13751382
created and how they are assigned. See the documentation for
1376-
:meth:`add_argument` for details.
1383+
:meth:`!add_argument` for details.
13771384

13781385
* args_ - List of strings to parse. The default is taken from
13791386
:data:`sys.argv`.
@@ -1529,7 +1536,7 @@ This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
15291536
Beyond ``sys.argv``
15301537
^^^^^^^^^^^^^^^^^^^
15311538

1532-
Sometimes it may be useful to have an ArgumentParser parse arguments other than those
1539+
Sometimes it may be useful to have an :class:`ArgumentParser` parse arguments other than those
15331540
of :data:`sys.argv`. This can be accomplished by passing a list of strings to
15341541
:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
15351542
interactive prompt::
@@ -1587,9 +1594,9 @@ Other utilities
15871594
Sub-commands
15881595
^^^^^^^^^^^^
15891596

1590-
.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1597+
.. method:: ArgumentParser.add_subparsers(*, [title], [description], [prog], \
15911598
[parser_class], [action], \
1592-
[option_strings], [dest], [required], \
1599+
[dest], [required], \
15931600
[help], [metavar])
15941601

15951602
Many programs split up their functionality into a number of subcommands,
@@ -1598,11 +1605,11 @@ Sub-commands
15981605
this way can be a particularly good idea when a program performs several
15991606
different functions which require different kinds of command-line arguments.
16001607
:class:`ArgumentParser` supports the creation of such subcommands with the
1601-
:meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1608+
:meth:`!add_subparsers` method. The :meth:`!add_subparsers` method is normally
16021609
called with no arguments and returns a special action object. This object
16031610
has a single method, :meth:`~_SubParsersAction.add_parser`, which takes a
1604-
command name and any :class:`ArgumentParser` constructor arguments, and
1605-
returns an :class:`ArgumentParser` object that can be modified as usual.
1611+
command name and any :class:`!ArgumentParser` constructor arguments, and
1612+
returns an :class:`!ArgumentParser` object that can be modified as usual.
16061613

16071614
Description of parameters:
16081615

@@ -1618,7 +1625,7 @@ Sub-commands
16181625
subparser argument
16191626

16201627
* *parser_class* - class which will be used to create sub-parser instances, by
1621-
default the class of the current parser (e.g. ArgumentParser)
1628+
default the class of the current parser (e.g. :class:`ArgumentParser`)
16221629

16231630
* action_ - the basic type of action to be taken when this argument is
16241631
encountered at the command line
@@ -1799,7 +1806,7 @@ Sub-commands
17991806
Namespace(subparser_name='2', y='frobble')
18001807

18011808
.. versionchanged:: 3.7
1802-
New *required* keyword argument.
1809+
New *required* keyword-only parameter.
18031810

18041811

18051812
FileType objects
@@ -1852,7 +1859,7 @@ Argument groups
18521859
"positional arguments" and "options" when displaying help
18531860
messages. When there is a better conceptual grouping of arguments than this
18541861
default one, appropriate groups can be created using the
1855-
:meth:`add_argument_group` method::
1862+
:meth:`!add_argument_group` method::
18561863

18571864
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
18581865
>>> group = parser.add_argument_group('group')
@@ -1869,7 +1876,7 @@ Argument groups
18691876
has an :meth:`~ArgumentParser.add_argument` method just like a regular
18701877
:class:`ArgumentParser`. When an argument is added to the group, the parser
18711878
treats it just like a normal argument, but displays the argument in a
1872-
separate group for help messages. The :meth:`add_argument_group` method
1879+
separate group for help messages. The :meth:`!add_argument_group` method
18731880
accepts *title* and *description* arguments which can be used to
18741881
customize this display::
18751882

@@ -1906,16 +1913,16 @@ Argument groups
19061913
will be removed in the future.
19071914

19081915
.. deprecated:: 3.14
1909-
Passing prefix_chars_ to :meth:`add_argument_group`
1910-
is now deprecated.
1916+
Passing prefix_chars_ to :meth:`add_argument_group`
1917+
is now deprecated.
19111918

19121919

19131920
Mutual exclusion
19141921
^^^^^^^^^^^^^^^^
19151922

19161923
.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
19171924

1918-
Create a mutually exclusive group. :mod:`argparse` will make sure that only
1925+
Create a mutually exclusive group. :mod:`!argparse` will make sure that only
19191926
one of the arguments in the mutually exclusive group was present on the
19201927
command line::
19211928

@@ -2128,7 +2135,7 @@ Intermixed parsing
21282135
and :meth:`~ArgumentParser.parse_known_intermixed_args` methods
21292136
support this parsing style.
21302137

2131-
These parsers do not support all the argparse features, and will raise
2138+
These parsers do not support all the :mod:`!argparse` features, and will raise
21322139
exceptions if unsupported features are used. In particular, subparsers,
21332140
and mutually exclusive groups that include both
21342141
optionals and positionals are not supported.

0 commit comments

Comments
 (0)
0