]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Allow whitespace around a slash in fraction string inputs (GH-96496)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Fri, 2 Sep 2022 16:10:58 +0000 (11:10 -0500)
committerGitHub <noreply@github.com>
Fri, 2 Sep 2022 16:10:58 +0000 (11:10 -0500)
Doc/library/fractions.rst
Lib/fractions.py
Lib/test/test_fractions.py
Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst [new file with mode: 0644]

index 5f0ecf1f135ea5cfb62403904292ae5da3ce5611..3751800b3b11189430d884cb663dfbb2d6f39f5b 100644 (file)
@@ -98,6 +98,9 @@ another rational number, or from a string.
       :class:`Fraction` implements ``__int__`` now to satisfy
       ``typing.SupportsInt`` instance checks.
 
+   .. versionchanged:: 3.12
+      Space is allowed around the slash for string inputs: `Fraction('2 / 3')`.
+
    .. attribute:: numerator
 
       Numerator of the Fraction in lowest term.
index 738a0d4c301d43e445e3dd4df51334dff908b53b..43b72ae414381a7a602f46f36a5412bcf540da88 100644 (file)
@@ -26,7 +26,7 @@ _RATIONAL_FORMAT = re.compile(r"""
     (?=\d|\.\d)                           # lookahead for digit or .digit
     (?P<num>\d*|\d+(_\d+)*)               # numerator (possibly empty)
     (?:                                   # followed by
-       (?:/(?P<denom>\d+(_\d+)*))?        # an optional denominator
+       (?:\s*/\s*(?P<denom>\d+(_\d+)*))?  # an optional denominator
     |                                     # or
        (?:\.(?P<decimal>d*|\d+(_\d+)*))?  # an optional fractional part
        (?:E(?P<exp>[-+]?\d+(_\d+)*))?     # and optional exponent
index fc46e8674fc46e971017b03cb41d376cd2b4f748..7fa9dbea905b592ef6e45e1f78203e62c4d6f899 100644 (file)
@@ -162,6 +162,7 @@ class FractionTest(unittest.TestCase):
     def testFromString(self):
         self.assertEqual((5, 1), _components(F("5")))
         self.assertEqual((3, 2), _components(F("3/2")))
+        self.assertEqual((3, 2), _components(F("3 / 2")))
         self.assertEqual((3, 2), _components(F(" \n  +3/2")))
         self.assertEqual((-3, 2), _components(F("-3/2  ")))
         self.assertEqual((13, 2), _components(F("    013/02 \n  ")))
@@ -190,9 +191,6 @@ class FractionTest(unittest.TestCase):
         self.assertRaisesMessage(
             ValueError, "Invalid literal for Fraction: '/2'",
             F, "/2")
-        self.assertRaisesMessage(
-            ValueError, "Invalid literal for Fraction: '3 /2'",
-            F, "3 /2")
         self.assertRaisesMessage(
             # Denominators don't need a sign.
             ValueError, "Invalid literal for Fraction: '3/+2'",
diff --git a/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst b/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst
new file mode 100644 (file)
index 0000000..a5858f4
--- /dev/null
@@ -0,0 +1,2 @@
+Fraction literals now support whitespace around the forward slash,
+`Fraction('2 / 3')`.