Skip to content

Commit

Permalink
pythongh-121797: Add class method Fraction.from_number()
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
serhiy-storchaka committed Jul 15, 2024
1 parent 8303d32 commit 680a9df
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Doc/library/fractions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ another rational number, or from a string.
instance.


.. classmethod:: from_number(number)

Alternative constructor which only accepts a numeric argument
(instances of :class:`numbers.Integral`, :class:`numbers.Rational`,
:class:`float` or :class:`decimal.Decimal`), but not strings.

.. versionadded:: 3.14


.. method:: limit_denominator(max_denominator=1000000)

Finds and returns the closest :class:`Fraction` to ``self`` that has
Expand Down
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ ast

(Contributed by Bénédikt Tran in :gh:`121141`.)

fractions
---------

* Add alternative :class:`~fractions.Fraction` constructor
:meth:`Fraction.from_number() <fractions.Fraction.from_number>`.
(Contributed by Serhiy Storchaka in :gh:`121797`.)

os
--

Expand Down
19 changes: 19 additions & 0 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,25 @@ def __new__(cls, numerator=0, denominator=None):
self._denominator = denominator
return self

@classmethod
def from_number(cls, number):
"""Converts a finite real number to a rational number, exactly.
Beware that Fraction.from_number(0.3) != Fraction(3, 10).
"""
if type(number) is int:
return cls._from_coprime_ints(number, 1)

elif isinstance(number, numbers.Rational):
return cls._from_coprime_ints(number.numerator, number.denominator)

elif isinstance(number, (float, Decimal)):
return cls._from_coprime_ints(*number.as_integer_ratio())

else:
raise TypeError("argument should be a Rational instance")

@classmethod
def from_float(cls, f):
"""Converts a finite float to a rational number, exactly.
Expand Down
23 changes: 23 additions & 0 deletions Lib/test/test_fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,29 @@ def testFromDecimal(self):
ValueError, "cannot convert NaN to integer ratio",
F.from_decimal, Decimal("snan"))

def testFromNumber(self, cls=F):
def check(arg, numerator, denominator):
f = cls.from_number(arg)
self.assertIs(type(f), cls)
self.assertEqual(f.numerator, numerator)
self.assertEqual(f.denominator, denominator)

check(10, 10, 1)
check(2.5, 5, 2)
check(Decimal('2.5'), 5, 2)
check(F(22, 7), 22, 7)
check(DummyFraction(22, 7), 22, 7)
check(Rat(22, 7), 22, 7)
self.assertRaises(TypeError, cls.from_number, 3+4j)
self.assertRaises(TypeError, cls.from_number, '5/2')
self.assertRaises(TypeError, cls.from_number, [])
self.assertRaises(OverflowError, cls.from_number, float('inf'))
self.assertRaises(OverflowError, cls.from_number, Decimal('inf'))

def testFromNumber_subclass(self):
self.testFromNumber(DummyFraction)


def test_is_integer(self):
self.assertTrue(F(1, 1).is_integer())
self.assertTrue(F(-1, 1).is_integer())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add alternative :class:`~fractions.Fraction` constructor
:meth:`Fraction.from_number() <fractions.Fraction.from_number>`.

0 comments on commit 680a9df

Please sign in to comment.