10000 Allow whitespace around a slash in fraction string inputs (GH-96496) · python/cpython@656167d · GitHub
[go: up one dir, main page]

Skip to content

Commit 656167d

Browse files
authored
Allow whitespace around a slash in fraction string inputs (GH-96496)
1 parent 91f40f3 commit 656167d

File tree

4 files changed

+7
-4
lines changed

4 files changed

+7
-4
lines changed

Doc/library/fractions.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ another rational number, or from a string.
9898
:class:`Fraction` implements ``__int__`` now to satisfy
9999
``typing.SupportsInt`` instance checks.
100100

101+
.. versionchanged:: 3.12
102+
Space is allowed around the slash for string inputs: `Fraction('2 / 3')`.
103+
101104
.. attribute:: numerator
102105

103106
Numerator of the Fraction in lowest term.

Lib/fractions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
(?=\d|\.\d) # lookahead for digit or .digit
2727
(?P<num>\d*|\d+(_\d+)*) # numerator (possibly empty)
2828
(?: # followed by
29-
(?:/(?P<denom>\d+(_\d+)*))? # an optional denominator
29+
(?:\s*/\s*(?P<denom>\d+(_\d+)*))? # an optional denominator
3030
| # or
3131
(?:\.(?P<decimal>d*|\d+(_\d+)*))? # an optional fractional part
3232
(?:E(?P<exp>[-+]?\d+(_\d+)*))? # and optional exponent

Lib/test/test_fractions.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ def testInitFromDecimal(self):
162162
def testFromString(self):
163163
self.assertEqual((5, 1), _components(F("5")))
164164
self.assertEqual((3, 2), _components(F("3/2")))
165+
self.assertEqual((3, 2), _components(F("3 / 2")))
165166
self.assertEqual((3, 2), _components(F(" \n +3/2")))
166167
self.assertEqual((-3, 2), _components(F("-3/2 ")))
167168
self.assertEqual((13, 2), _components(F(" 013/02 \n ")))
@@ -190,9 +191,6 @@ def testFromString(self):
190191
self.assertRaisesMessage(
191192
ValueError, "Invalid literal for Fraction: '/2'",
192193
F, "/2")
193-
self.assertRaisesMessage(
194-
ValueError, "Invalid literal for Fraction: '3 /2'",
195-
F, "3 /2")
196194
self.assertRaisesMessage(
197195
# Denominators don't need a sign.
198196
ValueError, "Invalid literal for Fraction: '3/+2'",
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fraction literals now support whitespace around the forward slash,
2+
`Fraction('2 / 3')`.

0 commit comments

Comments
 (0)
0