Skip to content

Commit 0978018

Browse files
bpo-29298: Fix crash with required subparsers without dest (GH-3680) (GH-27304)
(cherry picked from commit 17575f7) Co-authored-by: Anthony Sottile <[email protected]>
1 parent 0f55d21 commit 0978018

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

Lib/argparse.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,8 @@ def _get_action_name(argument):
727727
return argument.metavar
728728
elif argument.dest not in (None, SUPPRESS):
729729
return argument.dest
730+
elif argument.choices:
731+
return '{' + ','.join(argument.choices) + '}'
730732
else:
731733
return None
732734

Lib/test/test_argparse.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,6 +2057,30 @@ def test_required_subparsers_default(self):
20572057
ret = parser.parse_args(())
20582058
self.assertIsNone(ret.command)
20592059

2060+
def test_required_subparsers_no_destination_error(self):
2061+
parser = ErrorRaisingArgumentParser()
2062+
subparsers = parser.add_subparsers(required=True)
2063+
subparsers.add_parser('foo')
2064+
subparsers.add_parser('bar')
2065+
with self.assertRaises(ArgumentParserError) as excinfo:
2066+
parser.parse_args(())
2067+
self.assertRegex(
2068+
excinfo.exception.stderr,
2069+
'error: the following arguments are required: {foo,bar}\n$'
2070+
)
2071+
2072+
def test_wrong_argument_subparsers_no_destination_error(self):
2073+
parser = ErrorRaisingArgumentParser()
2074+
subparsers = parser.add_subparsers(required=True)
2075+
subparsers.add_parser('foo')
2076+
subparsers.add_parser('bar')
2077+
with self.assertRaises(ArgumentParserError) as excinfo:
2078+
parser.parse_args(('baz',))
2079+
self.assertRegex(
2080+
excinfo.exception.stderr,
2081+
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
2082+
)
2083+
20602084
def test_optional_subparsers(self):
20612085
parser = ErrorRaisingArgumentParser()
20622086
subparsers = parser.add_subparsers(dest='command', required=False)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``TypeError`` when required subparsers without ``dest`` do not receive
2+
arguments. Patch by Anthony Sottile.

0 commit comments

Comments
 (0)