Skip to content

Commit

Permalink
Check default argument values against choices
Browse files Browse the repository at this point in the history
In `parse_args`, check also action default values, so that an exception
is raised if an argument's default is not in `choices`.

Add a test case to verify the exception is raised.
  • Loading branch information
rudyardrichter committed Jan 30, 2023
1 parent c1b1f51 commit 8484fbc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
5 changes: 3 additions & 2 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2128,8 +2128,9 @@ def consume_positionals(start_index):
isinstance(action.default, str) and
hasattr(namespace, action.dest) and
action.default is getattr(namespace, action.dest)):
setattr(namespace, action.dest,
self._get_value(action, action.default))
value = self._get_value(action, action.default)
self._check_value(action, value)
setattr(namespace, action.dest, value)

if required_actions:
self.error(_('the following arguments are required: %s') %
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5044,6 +5044,15 @@ def test_argument_error(self):
error = argparse.ArgumentError(None, msg)
self.assertEqual(str(error), msg)

def test_default_validates_against_choices(self):
parser = ErrorRaisingArgumentParser()
parser.add_argument('--choice-with-default', choices=['a', 'b'],
default='foo')
with self.assertRaises(ArgumentParserError) as cm:
parser.parse_args([])
msg = str(cm.exception)
self.assertRegex(msg, 'invalid choice')

# =======================
# ArgumentTypeError tests
# =======================
Expand Down

0 comments on commit 8484fbc

Please sign in to comment.