diff --git a/Lib/argparse.py b/Lib/argparse.py index d5a0afb4a33eee..df98999f875d9e 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -1209,7 +1209,8 @@ def __call__(self, parser, namespace, values, option_string=None): # 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, []) @@ -1843,11 +1844,6 @@ def parse_known_args(self, args=None, namespace=None): 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: @@ -1858,6 +1854,11 @@ def parse_known_args(self, args=None, namespace=None): 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) diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index d369d0fb28f4a3..99269103c5b57d 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -3079,6 +3079,12 @@ def test_set_defaults_on_parent_and_subparser(self): 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') diff --git a/Misc/NEWS.d/next/Library/2021-09-17-16-55-37.bpo-45235.sXnmPA.rst b/Misc/NEWS.d/next/Library/2021-09-17-16-55-37.bpo-45235.sXnmPA.rst new file mode 100644 index 00000000000000..871ec5281d3344 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-09-17-16-55-37.bpo-45235.sXnmPA.rst @@ -0,0 +1,2 @@ +Fix an issue where argparse would not preserve values in a provided namespace +when using a subparser with defaults. \ No newline at end of file