From d8a5dc85619bcf5f553a809090abe1a57e4a70cb Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sun, 29 Sep 2024 14:15:03 +0300 Subject: [PATCH] gh-61011: Fix inheriting mutually exclusive groups from parent parsers Co-authored-by: Dougal J. Sutherland --- Lib/argparse.py | 6 +++++- Lib/test/test_argparse.py | 30 ++++++++++++++++++++++++++++++ Misc/ACKS | 1 + 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Lib/argparse.py b/Lib/argparse.py index 504289192f3f96..c4f43e7d01bc33 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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 diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 15805937baaa97..a1e4eee0852782 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -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 # ============================== diff --git a/Misc/ACKS b/Misc/ACKS index d94cbacf888468..bc8ece71289c12 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -1814,6 +1814,7 @@ Reuben Sumner Eryk Sun Sanjay Sundaresan Marek Ć uppa +Dougal J. Sutherland Hisao Suzuki Kalle Svensson Andrew Svetlov