[Python-checkins] r60530 - in python/trunk/Lib: rational.py test/test_rational.py

mark.dickinson python-checkins at python.org
Sat Feb 2 18:16:13 CET 2008


Author: mark.dickinson
Date: Sat Feb  2 18:16:13 2008
New Revision: 60530

Modified:
   python/trunk/Lib/rational.py
   python/trunk/Lib/test/test_rational.py
Log:
Make the Rational constructor accept '3.' and '.2' as well as '3.2'.


Modified: python/trunk/Lib/rational.py
==============================================================================
--- python/trunk/Lib/rational.py	(original)
+++ python/trunk/Lib/rational.py	Sat Feb  2 18:16:13 2008
@@ -25,9 +25,18 @@
     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):

Modified: python/trunk/Lib/test/test_rational.py
==============================================================================
--- python/trunk/Lib/test/test_rational.py	(original)
+++ python/trunk/Lib/test/test_rational.py	Sat Feb  2 18:16:13 2008
@@ -78,6 +78,8 @@
 
         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 @@
             # 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)


More information about the Python-checkins mailing list