bpo-45235: Fix argparse overrides namespace with subparser defaults (GH-28420) (GH-28443)

This commit is contained in:
Miss Islington (bot) 2021-09-17 23:47:41 -07:00 committed by GitHub
parent 6e151ff6fc
commit a18d52269a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 6 deletions

View File

@ -1208,7 +1208,8 @@ class _SubParsersAction(Action):
# namespace for the relevant parts.
subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
for key, value in vars(subnamespace).items():
setattr(namespace, key, value)
if not hasattr(namespace, key):
setattr(namespace, key, value)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
@ -1842,11 +1843,6 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
if action.default is not SUPPRESS:
setattr(namespace, action.dest, action.default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
if self.exit_on_error:
try:
@ -1857,6 +1853,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
else:
namespace, args = self._parse_known_args(args, namespace)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)

View File

@ -3057,6 +3057,12 @@ class TestSetDefaults(TestCase):
xparser.set_defaults(foo=2)
self.assertEqual(NS(foo=2), parser.parse_args(['X']))
def test_set_defaults_on_subparser_with_namespace(self):
parser = argparse.ArgumentParser()
xparser = parser.add_subparsers().add_parser('X')
xparser.set_defaults(foo=1)
self.assertEqual(NS(foo=2), parser.parse_args(['X'], NS(foo=2)))
def test_set_defaults_same_as_add_argument(self):
parser = ErrorRaisingArgumentParser()
parser.set_defaults(w='W', x='X', y='Y', z='Z')

View File

@ -0,0 +1,2 @@
Fix an issue where argparse would not preserve values in a provided namespace
when using a subparser with defaults.