Skip to content

gh-109990: Fixed argparser parsing optional arguments with same prefix #124000

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 7 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
18 changes: 18 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2234,6 +2234,18 @@ def _match_arguments_partial(self, actions, arg_strings_pattern):
# return the list of arg string counts
return result

def _extract_optional_arguments(self):
optionals = []

for action in self._actions:
if not isinstance(action, _SubParsersAction):
continue
if hasattr(action, 'choices'):
for choices in action.choices.values():
for action in choices._actions:
optionals.extend(action.option_strings)
return optionals

def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
Expand Down Expand Up @@ -2262,6 +2274,12 @@ def _parse_optional(self, arg_string):
# and all actions in the parser for possible interpretations
option_tuples = self._get_option_tuples(arg_string)

# if the parameter string exists,
# similar matching exception isn't thrown
optionals = self._extract_optional_arguments()
if arg_string in optionals:
return None

# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Enhance handling of optional arguments in the :meth:`argparse.ArgumentParser.add_argument`
of the :class:`argparse.ArgumentParser` in the :mod:`argparse`.
Loading