]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-123945: Update regex for parsing negative numbers that contain underscores (#123970)
authorSavannah Ostrowski <savannahostrowski@gmail.com>
Tue, 17 Sep 2024 06:30:17 +0000 (23:30 -0700)
committerGitHub <noreply@github.com>
Tue, 17 Sep 2024 06:30:17 +0000 (23:30 -0700)
---------

Co-authored-by: Brandt Bucher <brandtbucher@gmail.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-09-11-19-05-32.gh-issue-123945.jLwybB.rst [new file with mode: 0644]

index 100ef9f55cd2f78a2b5f09c155c3e009aafb5b6d..a88a8c65c40a1dd4c2762d89f9089324b1fac32a 100644 (file)
@@ -1360,7 +1360,7 @@ class _ActionsContainer(object):
         self._defaults = {}
 
         # determines whether an "option" looks like a negative number
-        self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
+        self._negative_number_matcher = _re.compile(r'^-\d[\d_]*(\.\d[\d_]*)?$')
 
         # whether or not there are any optionals that look like negative
         # numbers -- uses a list so it can be shared and edited
index fd111be18aed6eb5178f63656b8cd5efd4404583..584462b741ee9965b2343bc551f676408e4b1da9 100644 (file)
@@ -2093,6 +2093,26 @@ class TestActionExtend(ParserTestCase):
     ]
 
 
+class TestNegativeNumber(ParserTestCase):
+    """Test parsing negative numbers"""
+
+    argument_signatures = [
+        Sig('--int', type=int),
+        Sig('--float', type=float),
+    ]
+    failures = [
+        '--float -_.45',
+        '--float -1__000.0',
+        '--int -1__000',
+    ]
+    successes = [
+        ('--int -1000 --float -1000.0', NS(int=-1000, float=-1000.0)),
+        ('--int -1_000 --float -1_000.0', NS(int=-1000, float=-1000.0)),
+        ('--int -1_000_000 --float -1_000_000.0', NS(int=-1000000, float=-1000000.0)),
+        ('--float -1_000.0', NS(int=None, float=-1000.0)),
+        ('--float -1_000_000.0_0', NS(int=None, float=-1000000.0)),
+    ]
+
 class TestInvalidAction(TestCase):
     """Test invalid user defined Action"""
 
diff --git a/Misc/NEWS.d/next/Library/2024-09-11-19-05-32.gh-issue-123945.jLwybB.rst b/Misc/NEWS.d/next/Library/2024-09-11-19-05-32.gh-issue-123945.jLwybB.rst
new file mode 100644 (file)
index 0000000..26b0ac8
--- /dev/null
@@ -0,0 +1 @@
+Fix a bug where :mod:`argparse` doesn't recognize negative numbers with underscores