Skip to content

Commit 3597991

Browse files
serhiy-storchakamiss-islington
authored andcommitted
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='?'. (cherry picked from commit 9bcadf5) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 65103ad commit 3597991

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
@@ -2516,7 +2516,7 @@ def _get_values(self, action, arg_strings):
25162516
value = action.const
25172517
else:
25182518
value = action.default
2519-
if isinstance(value, str):
2519+
if isinstance(value, str) and value is not SUPPRESS:
25202520
value = self._get_value(action, value)
25212521
self._check_value(action, value)
25222522

Lib/test/test_argparse.py

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

15761576
argument_signatures = [
1577-
Sig('foo', nargs='?', default=argparse.SUPPRESS),
1578-
Sig('bar', nargs='*', default=argparse.SUPPRESS),
1577+
Sig('foo', nargs='?', type=int, default=argparse.SUPPRESS),
1578+
Sig('bar', nargs='*', type=int, default=argparse.SUPPRESS),
15791579
Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1580+
Sig('--qux', nargs='?', type=int, default=argparse.SUPPRESS),
1581+
Sig('--quux', nargs='*', type=int, default=argparse.SUPPRESS),
15801582
]
1581-
failures = ['-x']
1583+
failures = ['-x', 'a', '1 a']
15821584
successes = [
15831585
('', NS()),
1584-
('a', NS(foo='a')),
1585-
('a b', NS(foo='a', bar=['b'])),
1586+
('1', NS(foo=1)),
1587+
('1 2', NS(foo=1, bar=[2])),
15861588
('--baz', NS(baz=True)),
1587-
('a --baz', NS(foo='a', baz=True)),
1588-
('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1589+
('1 --baz', NS(foo=1, baz=True)),
1590+
('--baz 1 2', NS(foo=1, bar=[2], baz=True)),
1591+
('--qux', NS(qux=None)),
1592+
('--qux 1', NS(qux=1)),
1593+
('--quux', NS(quux=[])),
1594+
('--quux 1 2', NS(quux=[1, 2])),
15891595
]
15901596

15911597

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)