Skip to content

Commit 85bc430

Browse files
mattwang44miss-islington
authored andcommitted
pythongh-136032: Fix argparse.BooleanOptionalAction doc (pythonGH-136133)
(cherry picked from commit 1953713) Co-authored-by: W. H. Wang <[email protected]>
1 parent 2b2cf81 commit 85bc430

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
@@ -839,23 +839,11 @@ how the command-line arguments should be handled. The supplied actions are:
839839
>>> parser.parse_args(['--version'])
840840
PROG 2.0
841841

842-
Only actions that consume command-line arguments (e.g. ``'store'``,
843-
``'append'`` or ``'extend'``) can be used with positional arguments.
844-
845-
.. class:: BooleanOptionalAction
846-
847-
You may also specify an arbitrary action by passing an :class:`Action` subclass or
848-
other object that implements the same interface. The :class:`!BooleanOptionalAction`
849-
is available in :mod:`!argparse` and adds support for boolean actions such as
850-
``--foo`` and ``--no-foo``::
851-
852-
>>> import argparse
853-
>>> parser = argparse.ArgumentParser()
854-
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
855-
>>> parser.parse_args(['--no-foo'])
856-
Namespace(foo=False)
857-
858-
.. versionadded:: 3.9
842+
You may also specify an arbitrary action by passing an :class:`Action` subclass
843+
(e.g. :class:`BooleanOptionalAction`) or other object that implements the same
844+
interface. Only actions that consume command-line arguments (e.g. ``'store'``,
845+
``'append'``, ``'extend'``, or custom actions with non-zero ``nargs``) can be used
846+
with positional arguments.
859847

860848
The recommended way to create a custom action is to extend :class:`Action`,
861849
overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` and
@@ -1429,6 +1417,21 @@ this API may be passed as the ``action`` parameter to
14291417
and return a string which will be used when printing the usage of the program.
14301418
If such method is not provided, a sensible default will be used.
14311419

1420+
.. class:: BooleanOptionalAction
1421+
1422+
A subclass of :class:`Action` for handling boolean flags with positive
1423+
and negative options. Adding a single argument such as ``--foo`` automatically
1424+
creates both ``--foo`` and ``--no-foo`` options, storing ``True`` and ``False``
1425+
respectively::
1426+
1427+
>>> import argparse
1428+
>>> parser = argparse.ArgumentParser()
1429+
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
1430+
>>> parser.parse_args(['--no-foo'])
1431+
Namespace(foo=False)
1432+
1433+
.. versionadded:: 3.9
1434+
14321435

14331436
The parse_args() method
14341437
-----------------------

0 commit comments

Comments
 (0)