Skip to content

Commit bdcdb0a

Browse files
[3.12] gh-80259: Fix conflict between type and default=SUPPRESS in argparse (GH-124519) (GH-124752)
type() no longer called for SUPPRESS. This only affects positional arguments with nargs='?'. (cherry picked from commit 9bcadf5) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 00fd32a commit bdcdb0a

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
@@ -1591,18 +1591,24 @@ class TestDefaultSuppress(ParserTestCase):
15911591
"""Test actions with suppressed defaults"""
15921592

15931593
argument_signatures = [
1594-
Sig('foo', nargs='?', default=argparse.SUPPRESS),
1595-
Sig('bar', nargs='*', default=argparse.SUPPRESS),
1594+
Sig('foo', nargs='?', type=int, default=argparse.SUPPRESS),
1595+
Sig('bar', nargs='*', type=int, default=argparse.SUPPRESS),
15961596
Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1597+
Sig('--qux', nargs='?', type=int, default=argparse.SUPPRESS),
1598+
Sig('--quux', nargs='*', type=int, default=argparse.SUPPRESS),
15971599
]
1598-
failures = ['-x']
1600+
failures = ['-x', 'a', '1 a']
15991601
successes = [
16001602
('', NS()),
1601-
('a', NS(foo='a')),
1602-
('a b', NS(foo='a', bar=['b'])),
1603+
('1', NS(foo=1)),
1604+
('1 2', NS(foo=1, bar=[2])),
16031605
('--baz', NS(baz=True)),
1604-
('a --baz', NS(foo='a', baz=True)),
1605-
('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1606+
('1 --baz', NS(foo=1, baz=True)),
1607+
('--baz 1 2', NS(foo=1, bar=[2], baz=True)),
1608+
('--qux', NS(qux=None)),
1609+
('--qux 1', NS(qux=1)),
1610+
('--quux', NS(quux=[])),
1611+
('--quux 1 2', NS(quux=[1, 2])),
16061612
]
16071613

16081614

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)