pythonfractionspython-fractions

Taking the reciprocal of a Fraction


I want to take the reciprocal of Fraction in python, and do so in-place. The Fraction class does not provide a method for doing so (in my knowledge). I tried to just swap numerator and denominator:

f = Fraction(2, 3)
f.numerator, f.denominator = f.denominator, f.numerator

but it resulted in an AttributeError: can't set attribute.

I've also used the method of just constructing an new Fraction:

f = Fraction(2, 3)
f = Fraction(f.denominator, f.numerator)

which does in fact work, but creating a new object and deleting the old one doesn't seem very 'pythonic', i.e. unnecessarily complex. Is there a better way to take the reciprocal?


Solution

  • from fractions import Fraction
    
    spam = Fraction(2, 3)
    eggs = spam ** -1
    print(repr(eggs))
    

    output

    Fraction(3, 2)
    

    EDIT: As suggested in comments by @martineau 1 / spam also works:

    from fractions import Fraction
    
    spam = Fraction(2, 3)
    eggs = 1 / spam 
    print(repr(eggs))