Skip to content

Commit

Permalink
bpo-45235: Revert an argparse bugfix that caused a regression (python…
Browse files Browse the repository at this point in the history
…GH-29525)

* Revert "bpo-45235: Fix argparse overrides namespace with subparser defaults (pythonGH-28420) (pythonGH-28443)"

This reverts commit a18d522.
  • Loading branch information
rhettinger authored and remykarem committed Jan 30, 2022
1 parent d31875c commit 2118cb7
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 13 deletions.
13 changes: 6 additions & 7 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1210,8 +1210,7 @@ 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():
if not hasattr(namespace, key):
setattr(namespace, key, value)
setattr(namespace, key, value)

if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
Expand Down Expand Up @@ -1845,6 +1844,11 @@ 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:
Expand All @@ -1855,11 +1859,6 @@ 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)
Expand Down
6 changes: 0 additions & 6 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3114,12 +3114,6 @@ 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')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Reverted an argparse bugfix that caused regression in the handling of
default arguments for subparsers. This prevented leaf level arguments from
taking precedence over root level arguments.

0 comments on commit 2118cb7

Please sign in to comment.