From 656167db81a53934da55d90ed431449d8a4fc14b Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Fri, 2 Sep 2022 11:10:58 -0500 Subject: Allow whitespace around a slash in fraction string inputs (GH-96496) --- Doc/library/fractions.rst | 3 +++ Lib/fractions.py | 2 +- Lib/test/test_fractions.py | 4 +--- .../next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst | 2 ++ 4 files changed, 7 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst diff --git a/Doc/library/fractions.rst b/Doc/library/fractions.rst index 5f0ecf1..3751800 100644 --- a/Doc/library/fractions.rst +++ b/Doc/library/fractions.rst @@ -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. diff --git a/Lib/fractions.py b/Lib/fractions.py index 738a0d4..43b72ae 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -26,7 +26,7 @@ _RATIONAL_FORMAT = re.compile(r""" (?=\d|\.\d) # lookahead for digit or .digit (?P\d*|\d+(_\d+)*) # numerator (possibly empty) (?: # followed by - (?:/(?P\d+(_\d+)*))? # an optional denominator + (?:\s*/\s*(?P\d+(_\d+)*))? # an optional denominator | # or (?:\.(?Pd*|\d+(_\d+)*))? # an optional fractional part (?:E(?P[-+]?\d+(_\d+)*))? # and optional exponent diff --git a/Lib/test/test_fractions.py b/Lib/test/test_fractions.py index fc46e86..7fa9dbe 100644 --- a/Lib/test/test_fractions.py +++ b/Lib/test/test_fractions.py @@ -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 "))) @@ -191,9 +192,6 @@ class FractionTest(unittest.TestCase): 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'", F, "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 index 0000000..a5858f4 --- /dev/null +++ b/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst @@ -0,0 +1,2 @@ +Fraction literals now support whitespace around the forward slash, +`Fraction('2 / 3')`. -- cgit v0.12