Skip to content

Commit ad7340e

Browse files
authored
gh-92445 Improve interaction between nargs="*" and choices() (GH-92565)
1 parent cd492d4 commit ad7340e

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

Lib/argparse.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2477,9 +2477,11 @@ def _get_values(self, action, arg_strings):
24772477
not action.option_strings):
24782478
if action.default is not None:
24792479
value = action.default
2480+
self._check_value(action, value)
24802481
else:
2482+
# since arg_strings is always [] at this point
2483+
# there is no need to use self._check_value(action, value)
24812484
value = arg_strings
2482-
self._check_value(action, value)
24832485

24842486
# single argument or optional argument produces a single value
24852487
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:

Lib/test/test_argparse.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5230,6 +5230,13 @@ def test_mixed(self):
52305230
self.assertEqual(NS(v=3, spam=True, badger="B"), args)
52315231
self.assertEqual(["C", "--foo", "4"], extras)
52325232

5233+
def test_zero_or_more_optional(self):
5234+
parser = argparse.ArgumentParser()
5235+
parser.add_argument('x', nargs='*', choices=('x', 'y'))
5236+
args = parser.parse_args([])
5237+
self.assertEqual(NS(x=[]), args)
5238+
5239+
52335240
# ===========================
52345241
# parse_intermixed_args tests
52355242
# ===========================
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a bug in :mod:`argparse` where `nargs="*"` would raise an error instead of returning
2+
an empty list when 0 arguments were supplied if choice was also defined in
3+
``parser.add_argument``.

0 commit comments

Comments
 (0)