Skip to content

GH-103219: Fix optional args incorrectly being processed as required args #123931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixes a bug in argparse where optional args are incorrectly processed as required args
Loading