Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8921208

Browse files
savannahostrowskibrandtbucherhauntsaninja
authored andcommitted
GH-123945: Update regex for parsing negative numbers that contain underscores (#123970)
--------- Co-authored-by: Brandt Bucher <[email protected]> Co-authored-by: Shantanu <[email protected]>
1 parent 3cc43e0 commit 8921208

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

Lib/argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1360,7 +1360,7 @@ def __init__(self,
13601360
self._defaults = {}
13611361

13621362
# determines whether an "option" looks like a negative number
1363-
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1363+
self._negative_number_matcher = _re.compile(r'^-\d[\d_]*(\.\d[\d_]*)?$')
13641364

13651365
# whether or not there are any optionals that look like negative
13661366
# numbers -- uses a list so it can be shared and edited

Lib/test/test_argparse.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2093,6 +2093,26 @@ class TestActionExtend(ParserTestCase):
20932093
]
20942094

20952095

2096+
class TestNegativeNumber(ParserTestCase):
2097+
"""Test parsing negative numbers"""
2098+
2099+
argument_signatures = [
2100+
Sig('--int', type=int),
2101+
Sig('--float', type=float),
2102+
]
2103+
failures = [
2104+
'--float -_.45',
2105+
'--float -1__000.0',
2106+
'--int -1__000',
2107+
]
2108+
successes = [
2109+
('--int -1000 --float -1000.0', NS(int=-1000, float=-1000.0)),
2110+
('--int -1_000 --float -1_000.0', NS(int=-1000, float=-1000.0)),
2111+
('--int -1_000_000 --float -1_000_000.0', NS(int=-1000000, float=-1000000.0)),
2112+
('--float -1_000.0', NS(int=None, float=-1000.0)),
2113+
('--float -1_000_000.0_0', NS(int=None, float=-1000000.0)),
2114+
]
2115+
20962116
class TestInvalidAction(TestCase):
20972117
"""Test invalid user defined Action"""
20982118

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a bug where :mod:`argparse` doesn't recognize negative numbers with underscores

0 commit comments

Comments
 (0)