diff --git a/Lib/argparse.py b/Lib/argparse.py index 100ef9f55cd2f7..e9d2ea34c0b122 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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: @@ -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 diff --git a/Misc/NEWS.d/next/Library/2024-09-12-09-52-15.gh-issue-109990.belDmD.rst b/Misc/NEWS.d/next/Library/2024-09-12-09-52-15.gh-issue-109990.belDmD.rst new file mode 100644 index 00000000000000..71ab661b238c0f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-12-09-52-15.gh-issue-109990.belDmD.rst @@ -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`.