Skip to content

Commit 9bcadf5

Browse files
pythongh-80259: Fix conflict between type and default=SUPPRESS in argparse (pythonGH-124519)
type() no longer called for SUPPRESS. This only affects positional arguments with nargs='?'.
1 parent 49e105f commit 9bcadf5

File tree

3 files changed

+16
-8
lines changed

3 files changed

+16
-8
lines changed

Lib/argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2483,7 +2483,7 @@ def _get_values(self, action, arg_strings):
24832483
value = action.const
24842484
else:
24852485
value = action.default
2486-
if isinstance(value, str):
2486+
if isinstance(value, str) and value is not SUPPRESS:
24872487
value = self._get_value(action, value)
24882488
self._check_value(action, value)
24892489

Lib/test/test_argparse.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,18 +1587,24 @@ class TestDefaultSuppress(ParserTestCase):
15871587
"""Test actions with suppressed defaults"""
15881588

15891589
argument_signatures = [
1590-
Sig('foo', nargs='?', default=argparse.SUPPRESS),
1591-
Sig('bar', nargs='*', default=argparse.SUPPRESS),
1590+
Sig('foo', nargs='?', type=int, default=argparse.SUPPRESS),
1591+
Sig('bar', nargs='*', type=int, default=argparse.SUPPRESS),
15921592
Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1593+
Sig('--qux', nargs='?', type=int, default=argparse.SUPPRESS),
1594+
Sig('--quux', nargs='*', type=int, default=argparse.SUPPRESS),
15931595
]
1594-
failures = ['-x']
1596+
failures = ['-x', 'a', '1 a']
15951597
successes = [
15961598
('', NS()),
1597-
('a', NS(foo='a')),
1598-
('a b', NS(foo='a', bar=['b'])),
1599+
('1', NS(foo=1)),
1600+
('1 2', NS(foo=1, bar=[2])),
15991601
('--baz', NS(baz=True)),
1600-
('a --baz', NS(foo='a', baz=True)),
1601-
('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1602+
('1 --baz', NS(foo=1, baz=True)),
1603+
('--baz 1 2', NS(foo=1, bar=[2], baz=True)),
1604+
('--qux', NS(qux=None)),
1605+
('--qux 1', NS(qux=1)),
1606+
('--quux', NS(quux=[])),
1607+
('--quux 1 2', NS(quux=[1, 2])),
16021608
]
16031609

16041610

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`argparse` support of positional arguments with ``nargs='?'``,
2+
``default=argparse.SUPPRESS`` and specified ``type``.

0 commit comments

Comments
 (0)