Skip to content

Commit 095715c

Browse files
[3.13] gh-136032: Fix argparse.BooleanOptionalAction doc (GH-136133) (#136330)
gh-136032: Fix `argparse.BooleanOptionalAction` doc (GH-136133) (cherry picked from commit 1953713) Co-authored-by: W. H. Wang <mattwang44@gmail.com>
1 parent f39103b commit 095715c

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

Doc/library/argparse.rst

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -744,23 +744,11 @@ how the command-line arguments should be handled. The supplied actions are:
744744
>>> parser.parse_args(['--version'])
745745
PROG 2.0
746746

747-
Only actions that consume command-line arguments (e.g. ``'store'``,
748-
``'append'`` or ``'extend'``) can be used with positional arguments.
749-
750-
.. class:: BooleanOptionalAction
751-
752-
You may also specify an arbitrary action by passing an :class:`Action` subclass or
753-
other object that implements the same interface. The :class:`!BooleanOptionalAction`
754-
is available in :mod:`!argparse` and adds support for boolean actions such as
755-
``--foo`` and ``--no-foo``::
756-
757-
>>> import argparse
758-
>>> parser = argparse.ArgumentParser()
759-
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
760-
>>> parser.parse_args(['--no-foo'])
761-
Namespace(foo=False)
762-
763-
.. versionadded:: 3.9
747+
You may also specify an arbitrary action by passing an :class:`Action` subclass
748+
(e.g. :class:`BooleanOptionalAction`) or other object that implements the same
749+
interface. Only actions that consume command-line arguments (e.g. ``'store'``,
750+
``'append'``, ``'extend'``, or custom actions with non-zero ``nargs``) can be used
751+
with positional arguments.
764752

765753
The recommended way to create a custom action is to extend :class:`Action`,
766754
overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` and
@@ -1337,6 +1325,21 @@ this API may be passed as the ``action`` parameter to
13371325
and return a string which will be used when printing the usage of the program.
13381326
If such method is not provided, a sensible default will be used.
13391327

1328+
.. class:: BooleanOptionalAction
1329+
1330+
A subclass of :class:`Action` for handling boolean flags with positive
1331+
and negative options. Adding a single argument such as ``--foo`` automatically
1332+
creates both ``--foo`` and ``--no-foo`` options, storing ``True`` and ``False``
1333+
respectively::
1334+
1335+
>>> import argparse
1336+
>>> parser = argparse.ArgumentParser()
1337+
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
1338+
>>> parser.parse_args(['--no-foo'])
1339+
Namespace(foo=False)
1340+
1341+
.. versionadded:: 3.9
1342+
13401343

13411344
The parse_args() method
13421345
-----------------------

0 commit comments

Comments
 (0)