]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-80259: Fix conflict between type and default=SUPPRESS in argparse (GH-124519)
authorSerhiy Storchaka <storchaka@gmail.com>
Sun, 29 Sep 2024 07:47:06 +0000 (10:47 +0300)
committerGitHub <noreply@github.com>
Sun, 29 Sep 2024 07:47:06 +0000 (10:47 +0300)
type() no longer called for SUPPRESS.

This only affects positional arguments with nargs='?'.

Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-09-25-18-08-29.gh-issue-80259.kO5Tw7.rst [new file with mode: 0644]

index 4506a5e3a378f489f2d447cbb7423f5b9e5a04a3..3c2023e69e9ad6eca3536428c2ca68f8fd7bfc2d 100644 (file)
@@ -2483,7 +2483,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
                 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)
 
index 26e32c30b4d1045c1717cac0557a7b1cb38e0adb..08f31c239950e0bc861edafc46f212887cc0bda0 100644 (file)
@@ -1587,18 +1587,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 (file)
index 0000000..bb451cd
--- /dev/null
@@ -0,0 +1,2 @@
+Fix :mod:`argparse` support of positional arguments with ``nargs='?'``,
+``default=argparse.SUPPRESS`` and specified ``type``.