diff --git a/Lib/argparse.py b/Lib/argparse.py index 100ef9f55cd2f7..b3087d111b64a6 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2130,7 +2130,9 @@ def consume_positionals(start_index): required_actions = [] for action in self._actions: if action not in seen_actions: - if action.required: + if (action.required and + action.default is None and + action.nargs not in (ZERO_OR_MORE, OPTIONAL)): required_actions.append(_get_action_name(action)) else: # Convert action default now instead of doing it before diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index fd111be18aed6e..9e313ca9c72a9a 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -6091,6 +6091,13 @@ def test_required_args(self): 'the following arguments are required: bar, baz', self.parser.parse_args, []) + def test_required_and_optional(self): + self.parser.add_argument('bar') + self.parser.add_argument('baz', nargs='*') + self.assertRaisesRegex(argparse.ArgumentError, + 'the following arguments are required: bar', + self.parser.parse_args, []) + def test_required_mutually_exclusive_args(self): group = self.parser.add_mutually_exclusive_group(required=True) group.add_argument('--bar') diff --git a/Misc/NEWS.d/next/Library/2024-09-11-03-21-56.gh-issue-103219.F5atBD.rst b/Misc/NEWS.d/next/Library/2024-09-11-03-21-56.gh-issue-103219.F5atBD.rst new file mode 100644 index 00000000000000..b35be7b69ec4dd --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-11-03-21-56.gh-issue-103219.F5atBD.rst @@ -0,0 +1 @@ +Fixes a bug in argparse where optional args are incorrectly processed as required args