Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions Doc/library/fractions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,28 @@ A Fraction instance can be constructed from a pair of integers, from
another rational number, or from a string.

.. class:: Fraction(numerator=0, denominator=1)
Fraction(other_fraction)
Fraction(float)
Fraction(decimal)
Fraction(number)
Fraction(string)

The first version requires that *numerator* and *denominator* are instances
of :class:`numbers.Rational` and returns a new :class:`Fraction` instance
with value ``numerator/denominator``. If *denominator* is ``0``, it
raises a :exc:`ZeroDivisionError`. The second version requires that
*other_fraction* is an instance of :class:`numbers.Rational` and returns a
:class:`Fraction` instance with the same value. The next two versions accept
either a :class:`float` or a :class:`decimal.Decimal` instance, and return a
:class:`Fraction` instance with exactly the same value. Note that due to the
raises a :exc:`ZeroDivisionError`.

The second version requires that
*number* is an instance of :class:`numbers.Rational` or is an instance
of :class:`numbers.Number` and has the :meth:`!as_integer_ratio` method
(this includes :class:`float` and :class:`decimal.Decimal`).
It returns a :class:`Fraction` instance with exactly the same value.
Assumed, that the :meth:`~as_integer_ratio` method returns a pair
of coprime integers and last one is positive.
Note that due to the
usual issues with binary floating-point (see :ref:`tut-fp-issues`), the
argument to ``Fraction(1.1)`` is not exactly equal to 11/10, and so
``Fraction(1.1)`` does *not* return ``Fraction(11, 10)`` as one might expect.
(But see the documentation for the :meth:`limit_denominator` method below.)
The last version of the constructor expects a string or unicode instance.

The last version of the constructor expects a string.
The usual form for this instance is::

[sign] numerator ['/' denominator]
Expand Down Expand Up @@ -110,6 +114,10 @@ another rational number, or from a string.
Formatting of :class:`Fraction` instances without a presentation type
now supports fill, alignment, sign handling, minimum width and grouping.

.. versionchanged:: 3.14
The :class:`Fraction` constructor now accepts any numbers with the
:meth:`!as_integer_ratio` method.

.. attribute:: numerator

Numerator of the Fraction in lowest term.
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
---------

Added support for converting any numbers that have the
:meth:`!as_integer_ratio` method to a :class:`~fractions.Fraction`.
(Contributed by Serhiy Storchaka in :gh:`82017`.)

os
--

Expand Down
8 changes: 4 additions & 4 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

"""Fraction, infinite-precision, rational numbers."""

from decimal import Decimal
import functools
import math
import numbers
Expand Down Expand Up @@ -244,7 +243,9 @@ def __new__(cls, numerator=0, denominator=None):
self._denominator = numerator.denominator
return self

elif isinstance(numerator, (float, Decimal)):
elif (isinstance(numerator, float) or
(isinstance(numerator, numbers.Number) and
hasattr(numerator, 'as_integer_ratio'))):
# Exact conversion
self._numerator, self._denominator = numerator.as_integer_ratio()
return self
Expand Down Expand Up @@ -278,8 +279,7 @@ def __new__(cls, numerator=0, denominator=None):
numerator = -numerator

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

elif type(numerator) is int is type(denominator):
pass # *very* normal case
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 @@ -354,6 +354,29 @@ def testInitFromDecimal(self):
self.assertRaises(OverflowError, F, Decimal('inf'))
self.assertRaises(OverflowError, F, Decimal('-inf'))

def testInitFromIntegerRatio(self):
class Ratio:
def __init__(self, ratio):
self._ratio = ratio
def as_integer_ratio(self):
return self._ratio
class RatioNumber(Ratio):
pass
numbers.Number.register(RatioNumber)

self.assertEqual((7, 3), _components(F(RatioNumber((7, 3)))))
Copy link
Contributor

@skirpichev skirpichev Jul 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.assertEqual((7, 3), _components(F(RatioNumber((7, 3)))))
# as_integer_ratio() output should be normalized; lets check that
# we just keep this unmodified
self.assertEqual((6, 4), _components(F(RatioNumber((6, 4)))))

Forgot that. I think, this should address Victor's note.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is invalid ratio. The result is undefined.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is invalid ratio.

Yeah, but test just checks that we don't touch as_integer_ratio() output.

# not a number
self.assertRaises(TypeError, F, Ratio((7, 3)))
# the type also has an "as_integer_ratio" attribute.
self.assertRaises(TypeError, F, RatioNumber)
# bad ratio
self.assertRaises(TypeError, F, RatioNumber(7))
self.assertRaises(ValueError, F, RatioNumber((7,)))
self.assertRaises(ValueError, F, RatioNumber((7, 3, 1)))
# only single-argument form
self.assertRaises(TypeError, F, RatioNumber((3, 7)), 11)
self.assertRaises(TypeError, F, 2, RatioNumber((-10, 9)))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test on a fraction which can be simplified, to test "It returns a :class:Fraction instance with exactly the same value." from the doc? For example, the ratio 6/4. (Test that the GCD is not computed to simplify the ratio.)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it is an illegal input. Existing implementations return a simple ratio, simplifying it or checking that it is simplified would be just a waste of time.


def testFromString(self):
self.assertEqual((5, 1), _components(F("5")))
self.assertEqual((3, 2), _components(F("3/2")))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added support for converting any numbers that have the
:meth:`!as_integer_ratio` method to a :class:`~fractions.Fraction`.