8000 GH-123945: Update regex for parsing negative numbers that contain underscores by savannahostrowski · Pull Request #123970 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

GH-123945: Update regex for parsing negative numbers that contain underscores #123970

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/argparse.py
8000
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+)?$')

# whether or not there are any optionals that look like negative
# numbers -- uses a list so it can be shared and edited
Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_argparse.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -5716,6 +5716,31 @@ def test_double_dash(self):
args = parser.parse_args(['--foo', 'a', 'b', '--', 'c', 'd'])
self.assertEqual(NS(foo=['a', 'b'], bar=['c', 'd']), args)

def test_negative_number_success(self):
parser = argparse.ArgumentParser()
parser.add_argument('--int', type=int)
parser.add_argument('--float', type=float)

args = parser.parse_args(['--int', '-1000', '--float', '-1000.0'])
self.assertEqual(NS(int=-1000, float=-1000.0), args)

args = parser.parse_args(['--int', '-1_000', '--float', '-1_000.0'])
self.assertEqual(NS(int=-1000, float=-1000.0), args)

args = parser.parse_args(['--int', '-1_000_000', '--float', '-1_000_000.0'])
self.assertEqual(NS(int=-1000000, float=-1000000.0), args)

def test_negative_float_failure(self):
parser = ErrorRaisingArgumentParser(prog='PROG')
parser.add_argument('--float', type=float)

with self.assertRaises(ArgumentParserError) as cm:
parser.parse_args(['--float', '-_.45'])
parser.parse_args(['--float', '-1__000.0'])
parser.parse_args(['--float', '-1_000.0_0'])

self.assertRegex(str(cm.exception), r'error: argument --float: expected one argument')


# ===========================
# parse_intermixed_args tests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a bug where argparse doesn't recognize negative numbers with underscores
Loading
0