Search code examples
pythonpython-3.xcomparefractions

How to compare Fraction objects in Python?


I have a use case of equating fractions. Found fractions module in Python.

Tried using operators like <, == and > and it seems working.

from fractions import Fraction
print(Fraction(5,2) == Fraction(10,4)) # returns True
print(Fraction(1,3) > Fraction(2, 3))  # return False

Is this the expected way of doing comparisons?

Could not find anything explicitly specified in the docs.

Can someone confirm this (with a link to the source where it is mentioned)?


Solution

  • Looking at the implementation of the fraction module, we can see that __eq__ is defined:

    def __eq__(a, b):
        """a == b"""
        if type(b) is int:
            return a._numerator == b and a._denominator == 1
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        ...
    

    And so are __lt__ and __gt__:

    def __lt__(a, b):
        """a < b"""
        return a._richcmp(b, operator.lt)
    
    def __gt__(a, b):
        """a > b"""
        return a._richcmp(b, operator.gt)
    

    So the == and </> operators will work as expected.