Skip to content

Commit f251540

Browse files
authored
Merge pull request #4592 from carlosmiei/argparse
feat(argparse): update to 3.11
2 parents 3dc1562 + ffe1b6e commit f251540

File tree

2 files changed

+123
-45
lines changed

2 files changed

+123
-45
lines changed

Lib/argparse.py

+53-15
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@
8989
import re as _re
9090
import sys as _sys
9191

92+
import warnings
93+
9294
from gettext import gettext as _, ngettext
9395

9496
SUPPRESS = '==SUPPRESS=='
@@ -151,6 +153,7 @@ def _copy_items(items):
151153
# Formatting Help
152154
# ===============
153155

156+
154157
class HelpFormatter(object):
155158
"""Formatter for generating usage messages and argument help strings.
156159
@@ -693,15 +696,27 @@ class ArgumentDefaultsHelpFormatter(HelpFormatter):
693696
"""
694697

695698
def _get_help_string(self, action):
699+
"""
700+
Add the default value to the option help message.
701+
702+
ArgumentDefaultsHelpFormatter and BooleanOptionalAction when it isn't
703+
already present. This code will do that, detecting cornercases to
704+
prevent duplicates or cases where it wouldn't make sense to the end
705+
user.
706+
"""
696707
help = action.help
697-
if '%(default)' not in action.help:
708+
if help is None:
709+
help = ''
710+
711+
if '%(default)' not in help:
698712
if action.default is not SUPPRESS:
699713
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
700714
if action.option_strings or action.nargs in defaulting_nargs:
701715
help += ' (default: %(default)s)'
702716
return help
703717

704718

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

719734

720-
721735
# =====================
722736
# Options and Arguments
723737
# =====================
@@ -752,7 +766,7 @@ def __str__(self):
752766
if self.argument_name is None:
753767
format = '%(message)s'
754768
else:
755-
format = 'argument %(argument_name)s: %(message)s'
769+
format = _('argument %(argument_name)s: %(message)s')
756770
return format % dict(message=self.message,
757771
argument_name=self.argument_name)
758772

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

877+
863878
class BooleanOptionalAction(Action):
864879
def __init__(self,
865880
option_strings,
@@ -879,9 +894,6 @@ def __init__(self,
879894
option_string = '--no-' + option_string[2:]
880895
_option_strings.append(option_string)
881896

882-
if help is not None and default is not None and default is not SUPPRESS:
883-
help += " (default: %(default)s)"
884-
885897
super().__init__(
886898
option_strings=_option_strings,
887899
dest=dest,
@@ -893,6 +905,7 @@ def __init__(self,
893905
help=help,
894906
metavar=metavar)
895907

908+
896909
def __call__(self, parser, namespace, values, option_string=None):
897910
if option_string in self.option_strings:
898911
setattr(namespace, self.dest, not option_string.startswith('--no-'))
@@ -941,7 +954,7 @@ class _StoreConstAction(Action):
941954
def __init__(self,
942955
option_strings,
943956
dest,
944-
const,
957+
const=None,
945958
default=None,
946959
required=False,
947960
help=None,
@@ -1036,7 +1049,7 @@ class _AppendConstAction(Action):
10361049
def __init__(self,
10371050
option_strings,
10381051
dest,
1039-
const,
1052+
const=None,
10401053
default=None,
10411054
required=False,
10421055
help=None,
@@ -1168,6 +1181,13 @@ def add_parser(self, name, **kwargs):
11681181

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

1184+
if name in self._name_parser_map:
1185+
raise ArgumentError(self, _('conflicting subparser: %s') % name)
1186+
for alias in aliases:
1187+
if alias in self._name_parser_map:
1188+
raise ArgumentError(
1189+
self, _('conflicting subparser alias: %s') % alias)
1190+
11711191
# create a pseudo-action to hold the choice help
11721192
if 'help' in kwargs:
11731193
help = kwargs.pop('help')
@@ -1648,6 +1668,14 @@ def _remove_action(self, action):
16481668
super(_ArgumentGroup, self)._remove_action(action)
16491669
self._group_actions.remove(action)
16501670

1671+
def add_argument_group(self, *args, **kwargs):
1672+
warnings.warn(
1673+
"Nesting argument groups is deprecated.",
1674+
category=DeprecationWarning,
1675+
stacklevel=2
1676+
)
1677+
return super().add_argument_group(*args, **kwargs)
1678+
16511679

16521680
class _MutuallyExclusiveGroup(_ArgumentGroup):
16531681

@@ -1668,6 +1696,14 @@ def _remove_action(self, action):
16681696
self._container._remove_action(action)
16691697
self._group_actions.remove(action)
16701698

1699+
def add_mutually_exclusive_group(self, *args, **kwargs):
1700+
warnings.warn(
1701+
"Nesting mutually exclusive groups is deprecated.",
1702+
category=DeprecationWarning,
1703+
stacklevel=2
1704+
)
1705+
return super().add_mutually_exclusive_group(*args, **kwargs)
1706+
16711707

16721708
class ArgumentParser(_AttributeHolder, _ActionsContainer):
16731709
"""Object for parsing command line strings into Python objects.
@@ -1857,8 +1893,7 @@ def parse_known_args(self, args=None, namespace=None):
18571893
if self.exit_on_error:
18581894
try:
18591895
namespace, args = self._parse_known_args(args, namespace)
1860-
except ArgumentError:
1861-
err = _sys.exc_info()[1]
1896+
except ArgumentError as err:
18621897
self.error(str(err))
18631898
else:
18641899
namespace, args = self._parse_known_args(args, namespace)
@@ -1962,7 +1997,11 @@ def consume_optional(start_index):
19621997
# arguments, try to parse more single-dash options out
19631998
# of the tail of the option string
19641999
chars = self.prefix_chars
1965-
if arg_count == 0 and option_string[1] not in chars:
2000+
if (
2001+
arg_count == 0
2002+
and option_string[1] not in chars
2003+
and explicit_arg != ''
2004+
):
19662005
action_tuples.append((action, [], option_string))
19672006
char = option_string[0]
19682007
option_string = char + explicit_arg[0]
@@ -2133,8 +2172,7 @@ def _read_args_from_files(self, arg_strings):
21332172
arg_strings.append(arg)
21342173
arg_strings = self._read_args_from_files(arg_strings)
21352174
new_arg_strings.extend(arg_strings)
2136-
except OSError:
2137-
err = _sys.exc_info()[1]
2175+
except OSError as err:
21382176
self.error(str(err))
21392177

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

24862524
# ArgumentTypeErrors indicate errors
2487-
except ArgumentTypeError:
2525+
except ArgumentTypeError as err:
24882526
name = getattr(action.type, '__name__', repr(action.type))
2489-
msg = str(_sys.exc_info()[1])
2527+
msg = str(err)
24902528
raise ArgumentError(action, msg)
24912529

24922530
# TypeErrors or ValueErrors also indicate errors

0 commit comments

Comments
 (0)