Skip to content

Commit 6a517c6

Browse files
Rémi Lapeyrematrixise
authored andcommitted
bpo-8538: Add support for boolean actions to argparse (GH-11478)
Co-Authored-By: remilapeyre <[email protected]>
1 parent 04f0bbf commit 6a517c6

File tree

4 files changed

+109
-15
lines changed

4 files changed

+109
-15
lines changed

Doc/library/argparse.rst

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -839,9 +839,19 @@ how the command-line arguments should be handled. The supplied actions are:
839839
Namespace(foo=['f1', 'f2', 'f3', 'f4'])
840840

841841
You may also specify an arbitrary action by passing an Action subclass or
842-
other object that implements the same interface. The recommended way to do
843-
this is to extend :class:`Action`, overriding the ``__call__`` method
844-
and optionally the ``__init__`` method.
842+
other object that implements the same interface. The ``BooleanOptionalAction``
843+
is available in ``argparse`` and adds support for boolean actions such as
844+
``--foo`` and ``--no-foo``::
845+
846+
>>> import argparse
847+
>>> parser = argparse.ArgumentParser()
848+
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
849+
>>> parser.parse_args(['--no-foo'])
850+
Namespace(foo=False)
851+
852+
The recommended way to create a custom action is to extend :class:`Action`,
853+
overriding the ``__call__`` method and optionally the ``__init__`` and
854+
``format_usage`` methods.
845855

846856
An example of a custom action::
847857

@@ -1361,6 +1371,9 @@ Action instances should be callable, so subclasses must override the
13611371
The ``__call__`` method may perform arbitrary actions, but will typically set
13621372
attributes on the ``namespace`` based on ``dest`` and ``values``.
13631373

1374+
Action subclasses can define a ``format_usage`` method that takes no argument
1375+
and return a string which will be used when printing the usage of the program.
1376+
If such method is not provided, a sensible default will be used.
13641377

13651378
The parse_args() method
13661379
-----------------------

Lib/argparse.py

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
'ArgumentParser',
6868
'ArgumentError',
6969
'ArgumentTypeError',
70+
'BooleanOptionalAction',
7071
'FileType',
7172
'HelpFormatter',
7273
'ArgumentDefaultsHelpFormatter',
@@ -454,7 +455,7 @@ def _format_actions_usage(self, actions, groups):
454455
# if the Optional doesn't take a value, format is:
455456
# -s or --long
456457
if action.nargs == 0:
457-
part = '%s' % option_string
458+
part = action.format_usage()
458459

459460
# if the Optional takes a value, format is:
460461
# -s ARGS or --long ARGS
@@ -842,9 +843,53 @@ def _get_kwargs(self):
842843
]
843844
return [(name, getattr(self, name)) for name in names]
844845

846+
def format_usage(self):
847+
return self.option_strings[0]
848+
845849
def __call__(self, parser, namespace, values, option_string=None):
846850
raise NotImplementedError(_('.__call__() not defined'))
847851

852+
class BooleanOptionalAction(Action):
853+
def __init__(self,
854+
option_strings,
855+
dest,
856+
const=None,
857+
default=None,
858+
type=None,
859+
choices=None,
860+
required=False,
861+
help=None,
862+
metavar=None):
863+
864+
_option_strings = []
865+
for option_string in option_strings:
866+
_option_strings.append(option_string)
867+
868+
if option_string.startswith('--'):
869+
option_string = '--no-' + option_string[2:]
870+
_option_strings.append(option_string)
871+
872+
if help is not None and default is not None:
873+
help += f" (default: {default})"
874+
875+
super().__init__(
876+
option_strings=_option_strings,
877+
dest=dest,
878+
nargs=0,
879+
default=default,
880+
type=type,
881+
choices=choices,
882+
required=required,
883+
help=help,
884+
metavar=metavar)
885+
886+
def __call__(self, parser, namespace, values, option_string=None):
887+
if option_string in self.option_strings:
888+
setattr(namespace, self.dest, not option_string.startswith('--no-'))
889+
890+
def format_usage(self):
891+
return ' | '.join(self.option_strings)
892+
848893

849894
class _StoreAction(Action):
850895

Lib/test/test_argparse.py

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,30 @@ class TestOptionalsActionStoreTrue(ParserTestCase):
686686
('--apple', NS(apple=True)),
687687
]
688688

689+
class TestBooleanOptionalAction(ParserTestCase):
690+
"""Tests BooleanOptionalAction"""
691+
692+
argument_signatures = [Sig('--foo', action=argparse.BooleanOptionalAction)]
693+
failures = ['--foo bar', '--foo=bar']
694+
successes = [
695+
('', NS(foo=None)),
696+
('--foo', NS(foo=True)),
697+
('--no-foo', NS(foo=False)),
698+
('--foo --no-foo', NS(foo=False)), # useful for aliases
699+
('--no-foo --foo', NS(foo=True)),
700+
]
701+
702+
class TestBooleanOptionalActionRequired(ParserTestCase):
703+
"""Tests BooleanOptionalAction required"""
704+
705+
argument_signatures = [
706+
Sig('--foo', required=True, action=argparse.BooleanOptionalAction)
707+
]
708+
failures = ['']
709+
successes = [
710+
('--foo', NS(foo=True)),
711+
('--no-foo', NS(foo=False)),
712+
]
689713

690714
class TestOptionalsActionAppend(ParserTestCase):
691715
"""Tests the append action for an Optional"""
@@ -3456,6 +3480,10 @@ class TestHelpUsage(HelpTestCase):
34563480
Sig('a', help='a'),
34573481
Sig('b', help='b', nargs=2),
34583482
Sig('c', help='c', nargs='?'),
3483+
Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction),
3484+
Sig('--bar', help='Whether to bar', default=True,
3485+
action=argparse.BooleanOptionalAction),
3486+
Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction),
34593487
]
34603488
argument_group_signatures = [
34613489
(Sig('group'), [
@@ -3466,26 +3494,32 @@ class TestHelpUsage(HelpTestCase):
34663494
])
34673495
]
34683496
usage = '''\
3469-
usage: PROG [-h] [-w W [W ...]] [-x [X [X ...]]] [-y [Y]] [-z Z Z Z]
3497+
usage: PROG [-h] [-w W [W ...]] [-x [X [X ...]]] [--foo | --no-foo]
3498+
[--bar | --no-bar]
3499+
[-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]]
3500+
[-z Z Z Z]
34703501
a b b [c] [d [d ...]] e [e ...]
34713502
'''
34723503
help = usage + '''\
34733504
34743505
positional arguments:
3475-
a a
3476-
b b
3477-
c c
3506+
a a
3507+
b b
3508+
c c
34783509
34793510
optional arguments:
3480-
-h, --help show this help message and exit
3481-
-w W [W ...] w
3482-
-x [X [X ...]] x
3511+
-h, --help show this help message and exit
3512+
-w W [W ...] w
3513+
-x [X [X ...]] x
3514+
--foo, --no-foo Whether to foo
3515+
--bar, --no-bar Whether to bar (default: True)
3516+
-f, --foobar, --no-foobar, --barfoo, --no-barfoo
34833517
34843518
group:
3485-
-y [Y] y
3486-
-z Z Z Z z
3487-
d d
3488-
e e
3519+
-y [Y] y
3520+
-z Z Z Z z
3521+
d d
3522+
e e
34893523
'''
34903524
version = ''
34913525

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add support for boolean actions like ``--foo`` and ``--no-foo`` to argparse.
2+
Patch contributed by Rémi Lapeyre.

0 commit comments

Comments
 (0)