Skip to content

feat(argparse): update to 3.11 #4592

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

Merged
merged 2 commits into from
Feb 28, 2023
Merged
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
68 changes: 53 additions & 15 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@
import re as _re
import sys as _sys

import warnings

from gettext import gettext as _, ngettext

SUPPRESS = '==SUPPRESS=='
Expand Down Expand Up @@ -151,6 +153,7 @@ def _copy_items(items):
# Formatting Help
# ===============


class HelpFormatter(object):
"""Formatter for generating usage messages and argument help strings.

Expand Down Expand Up @@ -693,15 +696,27 @@ class ArgumentDefaultsHelpFormatter(HelpFormatter):
"""

def _get_help_string(self, action):
"""
Add the default value to the option help message.

ArgumentDefaultsHelpFormatter and BooleanOptionalAction when it isn't
already present. This code will do that, detecting cornercases to
prevent duplicates or cases where it wouldn't make sense to the end
user.
"""
help = action.help
if '%(default)' not in action.help:
if help is None:
help = ''

if '%(default)' not in help:
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
return help



class MetavarTypeHelpFormatter(HelpFormatter):
"""Help message formatter which uses the argument 'type' as the default
metavar value (instead of the argument 'dest')
Expand All @@ -717,7 +732,6 @@ def _get_default_metavar_for_positional(self, action):
return action.type.__name__



# =====================
# Options and Arguments
# =====================
Expand Down Expand Up @@ -752,7 +766,7 @@ def __str__(self):
if self.argument_name is None:
format = '%(message)s'
else:
format = 'argument %(argument_name)s: %(message)s'
format = _('argument %(argument_name)s: %(message)s')
return format % dict(message=self.message,
argument_name=self.argument_name)

Expand Down Expand Up @@ -860,6 +874,7 @@ def format_usage(self):
def __call__(self, parser, namespace, values, option_string=None):
raise NotImplementedError(_('.__call__() not defined'))


class BooleanOptionalAction(Action):
def __init__(self,
option_strings,
Expand All @@ -879,9 +894,6 @@ def __init__(self,
option_string = '--no-' + option_string[2:]
_option_strings.append(option_string)

if help is not None and default is not None and default is not SUPPRESS:
help += " (default: %(default)s)"

super().__init__(
option_strings=_option_strings,
dest=dest,
Expand All @@ -893,6 +905,7 @@ def __init__(self,
help=help,
metavar=metavar)


def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.option_strings:
setattr(namespace, self.dest, not option_string.startswith('--no-'))
Expand Down Expand Up @@ -941,7 +954,7 @@ class _StoreConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
const=None,
default=None,
required=False,
help=None,
Expand Down Expand Up @@ -1036,7 +1049,7 @@ class _AppendConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
const=None,
default=None,
required=False,
help=None,
Expand Down Expand Up @@ -1168,6 +1181,13 @@ def add_parser(self, name, **kwargs):

aliases = kwargs.pop('aliases', ())

if name in self._name_parser_map:
raise ArgumentError(self, _('conflicting subparser: %s') % name)
for alias in aliases:
if alias in self._name_parser_map:
raise ArgumentError(
self, _('conflicting subparser alias: %s') % alias)

# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
Expand Down Expand Up @@ -1648,6 +1668,14 @@ def _remove_action(self, action):
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action)

def add_argument_group(self, *args, **kwargs):
warnings.warn(
"Nesting argument groups is deprecated.",
category=DeprecationWarning,
stacklevel=2
)
return super().add_argument_group(*args, **kwargs)


class _MutuallyExclusiveGroup(_ArgumentGroup):

Expand All @@ -1668,6 +1696,14 @@ def _remove_action(self, action):
self._container._remove_action(action)
self._group_actions.remove(action)

def add_mutually_exclusive_group(self, *args, **kwargs):
warnings.warn(
"Nesting mutually exclusive groups is deprecated.",
category=DeprecationWarning,
stacklevel=2
)
return super().add_mutually_exclusive_group(*args, **kwargs)


class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Expand Down Expand Up @@ -1857,8 +1893,7 @@ def parse_known_args(self, args=None, namespace=None):
if self.exit_on_error:
try:
namespace, args = self._parse_known_args(args, namespace)
except ArgumentError:
err = _sys.exc_info()[1]
except ArgumentError as err:
self.error(str(err))
else:
namespace, args = self._parse_known_args(args, namespace)
Expand Down Expand Up @@ -1962,7 +1997,11 @@ def consume_optional(start_index):
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
if (
arg_count == 0
and option_string[1] not in chars
and explicit_arg != ''
):
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
Expand Down Expand Up @@ -2133,8 +2172,7 @@ def _read_args_from_files(self, arg_strings):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
except OSError:
err = _sys.exc_info()[1]
except OSError as err:
self.error(str(err))

# return the modified argument list
Expand Down Expand Up @@ -2484,9 +2522,9 @@ def _get_value(self, action, arg_string):
result = type_func(arg_string)

# ArgumentTypeErrors indicate errors
except ArgumentTypeError:
except ArgumentTypeError as err:
name = getattr(action.type, '__name__', repr(action.type))
msg = str(_sys.exc_info()[1])
msg = str(err)
raise ArgumentError(action, msg)

# TypeErrors or ValueErrors also indicate errors
Expand Down
Loading