Skip to content

Commit c6691a7

Browse files
bpo-46080: fix argparse help generation exception in edge case (GH-30111)
Fix an uncaught exception during help text generation when argparse.BooleanOptionalAction is used with default=argparse.SUPPRESS and help is specified. (cherry picked from commit 9e87c0e) Co-authored-by: Felix Fontein <[email protected]>
1 parent e8e71c4 commit c6691a7

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

Lib/argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -878,7 +878,7 @@ def __init__(self,
878878
option_string = '--no-' + option_string[2:]
879879
_option_strings.append(option_string)
880880

881-
if help is not None and default is not None:
881+
if help is not None and default is not None and default is not SUPPRESS:
882882
help += " (default: %(default)s)"
883883

884884
super().__init__(

Lib/test/test_argparse.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3597,6 +3597,8 @@ class TestHelpUsage(HelpTestCase):
35973597
Sig('--bar', help='Whether to bar', default=True,
35983598
action=argparse.BooleanOptionalAction),
35993599
Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction),
3600+
Sig('--bazz', action=argparse.BooleanOptionalAction,
3601+
default=argparse.SUPPRESS, help='Bazz!'),
36003602
]
36013603
argument_group_signatures = [
36023604
(Sig('group'), [
@@ -3609,8 +3611,8 @@ class TestHelpUsage(HelpTestCase):
36093611
usage = '''\
36103612
usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo]
36113613
[--bar | --no-bar]
3612-
[-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]]
3613-
[-z Z Z Z]
3614+
[-f | --foobar | --no-foobar | --barfoo | --no-barfoo]
3615+
[--bazz | --no-bazz] [-y [Y]] [-z Z Z Z]
36143616
a b b [c] [d ...] e [e ...]
36153617
'''
36163618
help = usage + '''\
@@ -3627,6 +3629,7 @@ class TestHelpUsage(HelpTestCase):
36273629
--foo, --no-foo Whether to foo
36283630
--bar, --no-bar Whether to bar (default: True)
36293631
-f, --foobar, --no-foobar, --barfoo, --no-barfoo
3632+
--bazz, --no-bazz Bazz!
36303633
36313634
group:
36323635
-y [Y] y
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix exception in argparse help text generation if a
2+
:class:`argparse.BooleanOptionalAction` argument's default is
3+
``argparse.SUPPRESS`` and it has ``help`` specified. Patch by Felix Fontein.

0 commit comments

Comments
 (0)