From 35979913281bd84ac90e4ec6325c74a4d176dd41 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sun, 29 Sep 2024 10:47:06 +0300 Subject: [PATCH] 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 9bcadf589ab6f7b9d309290de7a80156b6905d35) Co-authored-by: Serhiy Storchaka --- Lib/argparse.py | 2 +- Lib/test/test_argparse.py | 20 ++++++++++++------- ...4-09-25-18-08-29.gh-issue-80259.kO5Tw7.rst | 2 ++ 3 files changed, 16 insertions(+), 8 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2024-09-25-18-08-29.gh-issue-80259.kO5Tw7.rst diff --git a/Lib/argparse.py b/Lib/argparse.py index d0302ad4fb6fb7..6584932e83387a 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2516,7 +2516,7 @@ def _get_values(self, action, arg_strings): value = action.const else: value = action.default - if isinstance(value, str): + if isinstance(value, str) and value is not SUPPRESS: value = self._get_value(action, value) self._check_value(action, value) diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 854a50feebd0cc..960d8a1b8452b2 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -1574,18 +1574,24 @@ class TestDefaultSuppress(ParserTestCase): """Test actions with suppressed defaults""" argument_signatures = [ - Sig('foo', nargs='?', default=argparse.SUPPRESS), - Sig('bar', nargs='*', default=argparse.SUPPRESS), + Sig('foo', nargs='?', type=int, default=argparse.SUPPRESS), + Sig('bar', nargs='*', type=int, default=argparse.SUPPRESS), Sig('--baz', action='store_true', default=argparse.SUPPRESS), + Sig('--qux', nargs='?', type=int, default=argparse.SUPPRESS), + Sig('--quux', nargs='*', type=int, default=argparse.SUPPRESS), ] - failures = ['-x'] + failures = ['-x', 'a', '1 a'] successes = [ ('', NS()), - ('a', NS(foo='a')), - ('a b', NS(foo='a', bar=['b'])), + ('1', NS(foo=1)), + ('1 2', NS(foo=1, bar=[2])), ('--baz', NS(baz=True)), - ('a --baz', NS(foo='a', baz=True)), - ('--baz a b', NS(foo='a', bar=['b'], baz=True)), + ('1 --baz', NS(foo=1, baz=True)), + ('--baz 1 2', NS(foo=1, bar=[2], baz=True)), + ('--qux', NS(qux=None)), + ('--qux 1', NS(qux=1)), + ('--quux', NS(quux=[])), + ('--quux 1 2', NS(quux=[1, 2])), ] diff --git a/Misc/NEWS.d/next/Library/2024-09-25-18-08-29.gh-issue-80259.kO5Tw7.rst b/Misc/NEWS.d/next/Library/2024-09-25-18-08-29.gh-issue-80259.kO5Tw7.rst new file mode 100644 index 00000000000000..bb451cdd9ae44c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-25-18-08-29.gh-issue-80259.kO5Tw7.rst @@ -0,0 +1,2 @@ +Fix :mod:`argparse` support of positional arguments with ``nargs='?'``, +``default=argparse.SUPPRESS`` and specified ``type``.