From 1dabdb25f83d55737c2154b63bc463240fd7bc03 Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Sat, 2 Feb 2008 17:16:13 +0000 Subject: [PATCH] Make the Rational constructor accept '3.' and '.2' as well as '3.2'. --- Lib/rational.py | 15 ++++++++++++--- Lib/test/test_rational.py | 6 ++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Lib/rational.py b/Lib/rational.py index bc2259bb543..c76cba3d074 100755 --- a/Lib/rational.py +++ b/Lib/rational.py @@ -25,9 +25,18 @@ def gcd(a, b): return a -_RATIONAL_FORMAT = re.compile( - r'^\s*(?P[-+]?)(?P\d+)' - r'(?:/(?P\d+)|\.(?P\d+))?\s*$') +_RATIONAL_FORMAT = re.compile(r""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by an optional + /(?P\d+) # / and denominator + | # or + \.(?P\d*) # decimal point and fractional part + )? + \s*\Z # and optional whitespace to finish +""", re.VERBOSE) class Rational(RationalAbc): diff --git a/Lib/test/test_rational.py b/Lib/test/test_rational.py index 1c378742a56..5679c5a1b2d 100644 --- a/Lib/test/test_rational.py +++ b/Lib/test/test_rational.py @@ -78,6 +78,8 @@ class RationalTest(unittest.TestCase): self.assertEquals((16, 5), _components(R(" 3.2 "))) self.assertEquals((-16, 5), _components(R(u" -3.2 "))) + self.assertEquals((-3, 1), _components(R(u" -3. "))) + self.assertEquals((3, 5), _components(R(u" .6 "))) self.assertRaisesMessage( @@ -113,6 +115,10 @@ class RationalTest(unittest.TestCase): # Don't accept combinations of decimals and rationals. ValueError, "Invalid literal for Rational: 3.2/7", R, "3.2/7") + self.assertRaisesMessage( + # Allow 3. and .3, but not . + ValueError, "Invalid literal for Rational: .", + R, ".") def testImmutable(self): r = R(7, 3)