Skip to content

Commit

Permalink
pythonGH-123945: Update regex for parsing negative numbers that conta…
Browse files Browse the repository at this point in the history
…in underscores (python#123970)

---------

Co-authored-by: Brandt Bucher <brandtbucher@gmail.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
  • Loading branch information
3 people authored Sep 17, 2024
1 parent 0a32c69 commit 14e5bdc
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1360,7 +1360,7 @@ def __init__(self,
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
Expand Down
20 changes: 20 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a bug where :mod:`argparse` doesn't recognize negative numbers with underscores

0 comments on commit 14e5bdc

Please sign in to comment.