Skip to content

Commit 4d81d5b

Browse files
serhiy-storchakamiss-islington
authored andcommitted
gh-80259: Fix conflict between type and default=SUPPRESS in argparse (GH-124519)
type() no longer called for SUPPRESS. This only affects positional arguments with nargs='?'. (cherry picked from commit 9bcadf5) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 80de976 commit 4d81d5b

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
@@ -2511,7 +2511,7 @@ def _get_values(self, action, arg_strings):
25112511
value = action.const
25122512
else:
25132513
value = action.default
2514-
if isinstance(value, str):
2514+
if isinstance(value, str) and value is not SUPPRESS:
25152515
value = self._get_value(action, value)
25162516
self._check_value(action, value)
25172517

Lib/test/test_argparse.py

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

15581558
argument_signatures = [
1559-
Sig('foo', nargs='?', default=argparse.SUPPRESS),
1560-
Sig('bar', nargs='*', default=argparse.SUPPRESS),
1559+
Sig('foo', nargs='?', type=int, default=argparse.SUPPRESS),
1560+
Sig('bar', nargs='*', type=int, default=argparse.SUPPRESS),
15611561
Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1562+
Sig('--qux', nargs='?', type=int, default=argparse.SUPPRESS),
1563+
Sig('--quux', nargs='*', type=int, default=argparse.SUPPRESS),
15621564
]
1563-
failures = ['-x']
1565+
failures = ['-x', 'a', '1 a']
15641566
successes = [
15651567
('', NS()),
1566-
('a', NS(foo='a')),
1567-
('a b', NS(foo='a', bar=['b'])),
1568+
('1', NS(foo=1)),
1569+
('1 2', NS(foo=1, bar=[2])),
15681570
('--baz', NS(baz=True)),
1569-
('a --baz', NS(foo='a', baz=True)),
1570-
('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1571+
('1 --baz', NS(foo=1, baz=True)),
1572+
('--baz 1 2', NS(foo=1, bar=[2], baz=True)),
1573+
('--qux', NS(qux=None)),
1574+
('--qux 1', NS(qux=1)),
1575+
('--quux', NS(quux=[])),
1576+
('--quux 1 2', NS(quux=[1, 2])),
15711577
]
15721578

15731579

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)