Skip to content

Commit 680a9df

Browse files
pythongh-121797: Add class method Fraction.from_number()
It is an alternative constructor which only accepts a single numeric argument. Unlike to Fraction.from_float() and Fraction.from_decimal() it accepts any real numbers supported by the standard constructor (int, float, Decimal, Rational numbers). Unlike to the standard constructor, it does not accept strings.
1 parent 8303d32 commit 680a9df

5 files changed

Lines changed: 60 additions & 0 deletions

File tree

β€ŽDoc/library/fractions.rstβ€Ž

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,15 @@ another rational number, or from a string.
157157
instance.
158158

159159

160+
.. classmethod:: from_number(number)
161+
162+
Alternative constructor which only accepts a numeric argument
163+
(instances of :class:`numbers.Integral`, :class:`numbers.Rational`,
164+
:class:`float` or :class:`decimal.Decimal`), but not strings.
165+
166+
.. versionadded:: 3.14
167+
168+
160169
.. method:: limit_denominator(max_denominator=1000000)
161170

162171
Finds and returns the closest :class:`Fraction` to ``self`` that has

β€ŽDoc/whatsnew/3.14.rstβ€Ž

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,13 @@ ast
9696

9797
(Contributed by BΓ©nΓ©dikt Tran in :gh:`121141`.)
9898

99+
fractions
100+
---------
101+
102+
* Add alternative :class:`~fractions.Fraction` constructor
103+
:meth:`Fraction.from_number() <fractions.Fraction.from_number>`.
104+
(Contributed by Serhiy Storchaka in :gh:`121797`.)
105+
99106
os
100107
--
101108

β€ŽLib/fractions.pyβ€Ž

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,25 @@ def __new__(cls, numerator=0, denominator=None):
305305
self._denominator = denominator
306306
return self
307307

308+
@classmethod
309+
def from_number(cls, number):
310+
"""Converts a finite real number to a rational number, exactly.
311+
312+
Beware that Fraction.from_number(0.3) != Fraction(3, 10).
313+
314+
"""
315+
if type(number) is int:
316+
return cls._from_coprime_ints(number, 1)
317+
318+
elif isinstance(number, numbers.Rational):
319+
return cls._from_coprime_ints(number.numerator, number.denominator)
320+
321+
elif isinstance(number, (float, Decimal)):
322+
return cls._from_coprime_ints(*number.as_integer_ratio())
323+
324+
else:
325+
raise TypeError("argument should be a Rational instance")
326+
308327
@classmethod
309328
def from_float(cls, f):
310329
"""Converts a finite float to a rational number, exactly.

β€ŽLib/test/test_fractions.pyβ€Ž

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,29 @@ def testFromDecimal(self):
559559
ValueError, "cannot convert NaN to integer ratio",
560560
F.from_decimal, Decimal("snan"))
561561

562+
def testFromNumber(self, cls=F):
563+
def check(arg, numerator, denominator):
564+
f = cls.from_number(arg)
565+
self.assertIs(type(f), cls)
566+
self.assertEqual(f.numerator, numerator)
567+
self.assertEqual(f.denominator, denominator)
568+
569+
check(10, 10, 1)
570+
check(2.5, 5, 2)
571+
check(Decimal('2.5'), 5, 2)
572+
check(F(22, 7), 22, 7)
573+
check(DummyFraction(22, 7), 22, 7)
574+
check(Rat(22, 7), 22, 7)
575+
self.assertRaises(TypeError, cls.from_number, 3+4j)
576+
self.assertRaises(TypeError, cls.from_number, '5/2')
577+
self.assertRaises(TypeError, cls.from_number, [])
578+
self.assertRaises(OverflowError, cls.from_number, float('inf'))
579+
self.assertRaises(OverflowError, cls.from_number, Decimal('inf'))
580+
581+
def testFromNumber_subclass(self):
582+
self.testFromNumber(DummyFraction)
583+
584+
562585
def test_is_integer(self):
563586
self.assertTrue(F(1, 1).is_integer())
564587
self.assertTrue(F(-1, 1).is_integer())
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add alternative :class:`~fractions.Fraction` constructor
2+
:meth:`Fraction.from_number() <fractions.Fraction.from_number>`.

0 commit comments

Comments
Β (0)