Skip to content

Commit

Permalink
[3.12] pythonGH-124321: Fix argparse negative number parsing to captu…
Browse files Browse the repository at this point in the history
…re -.5(pythonGH-124322)

(cherry picked from commit dc48312)

Co-authored-by: Savannah Ostrowski <savannahostrowski@gmail.com>
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
  • Loading branch information
savannahostrowski and AA-Turner committed Sep 23, 2024
1 parent dd2066f commit f6234ed
Show file tree
Hide file tree
Showing 2 changed files with 44 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 @@ -1405,7 +1405,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+)*)?|\.\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
43 changes: 43 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2092,6 +2092,49 @@ class TestActionExtend(ParserTestCase):
('--foo f1 --foo f2 f3 f4', NS(foo=['f1', 'f2', 'f3', 'f4'])),
]


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)),
('--float -.5', NS(int=None, float=-0.5)),
('--float -.5_000', NS(int=None, float=-0.5)),
]

class TestInvalidAction(TestCase):
"""Test invalid user defined Action"""

class ActionWithoutCall(argparse.Action):
pass

def test_invalid_type(self):
parser = argparse.ArgumentParser()

parser.add_argument('--foo', action=self.ActionWithoutCall)
self.assertRaises(NotImplementedError, parser.parse_args, ['--foo', 'bar'])

def test_modified_invalid_action(self):
parser = ErrorRaisingArgumentParser()
action = parser.add_argument('--foo')
# Someone got crazy and did this
action.type = 1
self.assertRaises(ArgumentParserError, parser.parse_args, ['--foo', 'bar'])


# ================
# Subparsers tests
# ================
Expand Down

0 comments on commit f6234ed

Please sign in to comment.