]> granicus.if.org Git - python/commitdiff
Make the Rational constructor accept '3.' and '.2' as well as '3.2'.
authorMark Dickinson <dickinsm@gmail.com>
Sat, 2 Feb 2008 17:16:13 +0000 (17:16 +0000)
committerMark Dickinson <dickinsm@gmail.com>
Sat, 2 Feb 2008 17:16:13 +0000 (17:16 +0000)
Lib/rational.py
Lib/test/test_rational.py

index bc2259bb5436337d5f6a71d71d02b65c545717fe..c76cba3d074a302ecf26979f0c4ba24e74bc9575 100755 (executable)
@@ -25,9 +25,18 @@ def gcd(a, b):
     return a
 
 
-_RATIONAL_FORMAT = re.compile(
-    r'^\s*(?P<sign>[-+]?)(?P<num>\d+)'
-    r'(?:/(?P<denom>\d+)|\.(?P<decimal>\d+))?\s*$')
+_RATIONAL_FORMAT = re.compile(r"""
+    \A\s*                      # optional whitespace at the start, then
+    (?P<sign>[-+]?)            # an optional sign, then
+    (?=\d|\.\d)                # lookahead for digit or .digit
+    (?P<num>\d*)               # numerator (possibly empty)
+    (?:                        # followed by an optional
+       /(?P<denom>\d+)         # / and denominator
+    |                          # or
+       \.(?P<decimal>\d*)      # decimal point and fractional part
+    )?
+    \s*\Z                      # and optional whitespace to finish
+""", re.VERBOSE)
 
 
 class Rational(RationalAbc):
index 1c378742a560258ba958e2cf4bb819e74f4bb6bf..5679c5a1b2d404f2a8b5a35b9f7bc5580d9d5762 100644 (file)
@@ -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)