Fraction object doesn't have __int__ but int(Fraction(...)) still works

226 views Asked by At

In Python, when you have an object you can convert it to an integer using the int function.

For example int(1.3) will return 1. This works internally by using the __int__ magic method of the object, in this particular case float.__int__.

In Python Fraction objects can be used to construct exact fractions.

from fractions import Fraction
x = Fraction(4, 3)

Fraction objects lack an __int__ method, but you can still call int() on them and get a sensible integer back. I was wondering how this was possible with no __int__ method being defined.

In [38]: x = Fraction(4, 3)

In [39]: int(x)
Out[39]: 1
1

There are 1 answers

2
User On BEST ANSWER

The __trunc__ method is used.

>>> class X(object):
    def __trunc__(self):
        return 2.


>>> int(X())
2

__float__ does not work

>>> class X(object):
    def __float__(self):
        return 2.

>>> int(X())
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(X())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'X'

The CPython source shows when __trunc__ is used.