Search code examples
pythonpython-3.xindexingfractions

How to work around Python object that does not support indexing?


Objective: to have two elements that can be called later in a script

Description: In the example below, I am only interested in the 0.25 value which will is represented by 1/4). I would like to have a value for the numerator (1) and the denominator (4). I am making use of Python's fractions module.

NUMBER = 5.25

from fractions import Fraction
import math

def express_partFraction(NUMBER):
    part = math.modf(NUMBER)[0] 
    return ((Fraction(part)))

express_partFraction(NUMBER)

Currently, I have the following returned which is not indexable:

Fraction(1, 4)

However, I am looking for something like the following:

numerator = express_partFraction(NUMBER)[0]
denominator = express_partFraction(NUMBER)[1]

Which generates this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-486-39196ec5b50b> in <module>()
     10 express_partFraction(NUMBER)
     11 
---> 12 numerator = express_partFraction(NUMBER)[0]
     13 denominator = express_partFraction(NUMBER)[1]

TypeError: 'Fraction' object does not support indexing

Solution

  • The Python 2.7 documentation omits the fact that Fraction objects have numerator and denominator attributes. You can find them in the Python 3 documentation.

    If you want to see what attributes an unknown object has, just use the dir() function:

    >>> x = Fraction(1, 2)
    >>> x.numerator
    1
    >>> x.denominator
    2
    >>> [a for a in dir(x) if not a.startswith('_')]
    ['conjugate', 'denominator', 'from_decimal', 'from_float', 'imag', 'limit_denominator', 'numerator', 'real']