Skip to content

Commit

Permalink
pythongh-61011: Fix inheriting mutually exclusive groups from parent …
Browse files Browse the repository at this point in the history
…parsers

Co-authored-by: Dougal J. Sutherland
  • Loading branch information
serhiy-storchaka committed Sep 29, 2024
1 parent 95e92ef commit d8a5dc8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1514,7 +1514,11 @@ def _add_container_actions(self, container):
# NOTE: if add_mutually_exclusive_group ever gains title= and
# description= then this code will need to be expanded as above
for group in container._mutually_exclusive_groups:
mutex_group = self.add_mutually_exclusive_group(
if group._container is container:
cont = self
else:
cont = title_group_map[group._container.title]
mutex_group = cont.add_mutually_exclusive_group(
required=group.required)

# map the actions to their new mutex group
Expand Down
30 changes: 30 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2904,6 +2904,36 @@ def test_groups_parents(self):
def test_wrong_type_parents(self):
self.assertRaises(TypeError, ErrorRaisingArgumentParser, parents=[1])

def test_mutex_groups_parents(self):
parent = ErrorRaisingArgumentParser(add_help=False)
g = parent.add_argument_group(title='g', description='gd')
g.add_argument('-w')
g.add_argument('-x')
m = g.add_mutually_exclusive_group()
m.add_argument('-y')
m.add_argument('-z')
parser = ErrorRaisingArgumentParser(parents=[parent])

self.assertRaises(ArgumentParserError, parser.parse_args,
['-y', 'Y', '-z', 'Z'])

parser_help = parser.format_help()
progname = self.main_program
self.assertEqual(parser_help, textwrap.dedent('''\
usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
optional arguments:
-h, --help show this help message and exit
g:
gd
-w W
-x X
-y Y
-z Z
'''.format(progname, ' ' if progname else '' )))

# ==============================
# Mutually exclusive group tests
# ==============================
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1814,6 +1814,7 @@ Reuben Sumner
Eryk Sun
Sanjay Sundaresan
Marek Šuppa
Dougal J. Sutherland
Hisao Suzuki
Kalle Svensson
Andrew Svetlov
Expand Down

0 comments on commit d8a5dc8

Please sign in to comment.