Python __int__ Method
Last modified November 18, 2026 Python 3.15
Calling int(obj) asks the object for an integer through its
__int__ method. The hook decides how the conversion happens,
which makes it useful for wrapper types that store measurements or structured
values. This article shows the call, the difference between truncation and
floor division, the rule that the method must return a real integer, and the
relationship to __index__.
Basic integer conversion
The int() built-in calls type(obj).__int__(obj)
and returns what the method gives back. A wrapper class typically converts
one of its stored attributes.
class Distance:
def __init__(self, metres):
self.metres = metres
def __int__(self):
print("__int__ called")
return int(self.metres)
def __repr__(self):
return f"Distance({self.metres})"
d = Distance(3.7)
print(int(d))
The trace confirms the hook is used. int(3.7) truncates the
fractional part and produces 3. A wrapper class can choose any rule it
wants; here it simply delegates to the built-in conversion of the stored
value.
$ python basic_int.py __int__ called 3
Rounding instead of truncating
The hook is free to round rather than truncate. Python's built-in
round() uses banker's rounding for halfway values, which is
worth remembering when writing a conversion for measurements.
class Celsius:
def __init__(self, temperature):
self.temperature = temperature
def __int__(self):
return round(self.temperature)
def __repr__(self):
return f"Celsius({self.temperature})"
for value in (36.6, 36.5, 37.5):
c = Celsius(value)
print(value, "->", int(c))
36.6 rounds up to 37. The exact halves 36.5 and 37.5 round to the nearest
even number, 36 and 38. If you need the schoolbook rule of always rounding
halves up, add 0.5 before truncating instead of using round().
$ python rounding_int.py 36.6 -> 37 36.5 -> 36 37.5 -> 38
Truncation is not floor division
The built-in int() truncates towards zero, while
// rounds towards negative infinity. A conversion that uses
// therefore gives a different answer for negative values — a
mistake the old version of this article glossed over.
class Half:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __int__(self):
return self.numerator // self.denominator
def __repr__(self):
return f"Half({self.numerator}, {self.denominator})"
for n in (-7, 7):
h = Half(n, 3)
print(n, "->", int(h), " built-in int(n / 3):", int(n / 3))
For -7 the hook returns -3 because -7 // 3 floors, but the
built-in conversion gives -2. To match int() semantics use
math.trunc on an exact rational, or simply truncate the
quotient; do not substitute // blindly.
$ python floor_vs_trunc.py -7 -> -3 built-in int(n / 3): -2 7 -> 2 built-in int(n / 3): 2
The method must return an int
Python checks the type of the returned value. Returning a float is an error, and the message names both the method and the type that was actually returned.
class Bad:
def __int__(self):
return 3.7
try:
int(Bad())
except TypeError as e:
print(type(e).__name__, e)
The conversion fails before int() produces a result. A
strictly checked return type keeps conversions predictable: callers can rely
on getting an integer or an explicit error, never a silently coerced value.
$ python bad_return.py TypeError Bad.__int__() must return an int, not float
__int__ and __index__ are different hooks
When a class defines both, int(obj) uses
__int__, while the integer-only protocol used by slicing,
range() and the hex() family uses
__index__. The two methods are called independently.
class Both:
def __int__(self):
print("__int__")
return 5
def __index__(self):
print("__index__")
return 2
b = Both()
print("int:", int(b))
print("index:", hex(b), bin(b), oct(b))
print("range:", list(range(b)))
int(b) printed 5 from __int__. Each of
hex, bin and oct called
__index__ separately, and so did range(), which
used the value 2. Implement __index__ when an object must act as
an exact integer index.
$ python int_vs_index.py __int__ int: 5 __index__ __index__ __index__ index: 0x2 0b10 0o2 __index__ range: [0, 1]
Falling back to __index__
If a class has no __int__, int() falls back to
__index__. This works because the index protocol guarantees a
lossless integer. Once __int__ exists, however, it is used even
if it fails.
class OnlyIndex:
def __index__(self):
print("__index__")
return 7
print(int(OnlyIndex()))
print(float(OnlyIndex()))
class BrokenInt:
def __int__(self):
print("BrokenInt.__int__")
return None
def __index__(self):
return 7
try:
int(BrokenInt())
except TypeError as e:
print(type(e).__name__, e)
The first object is converted through __index__, and
float() uses the same fallback. The second object defines a
broken __int__; Python calls it and reports the error instead of
trying the valid __index__.
$ python index_fallback.py __index__ 7 __index__ 7.0 BrokenInt.__int__ TypeError BrokenInt.__int__() must return an int, not NoneType
Combining attributes into one integer
A structured value can collapse several fields into a single integer. Packing colour channels into a 24-bit value is a common example and produces a stable, easy-to-check result.
class RGBColor:
def __init__(self, red, green, blue):
self.red = red
self.green = green
self.blue = blue
def __int__(self):
return (self.red << 16) | (self.green << 8) | self.blue
def __repr__(self):
return f"RGBColor({self.red}, {self.green}, {self.blue})"
color = RGBColor(255, 128, 0)
packed = int(color)
print(packed, hex(packed))
The three 8-bit channels occupy 24 bits: 0xFF0000 for red,
0x008000 for green and no blue. The printed value is a plain
integer; hex() is only used to show its familiar colour form.
$ python rgb_color.py 16744448 0xff8000
Returning a bool is deprecated
A bool is a subclass of int, so it currently
works as a return value. Python warns that this will be removed, so convert
it with int() inside the hook.
import warnings
class Flag:
def __int__(self):
return True
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
value = int(Flag())
print(value, [w.category.__name__ for w in caught])
class FixedFlag:
def __int__(self):
return int(True)
print(int(FixedFlag()))
The first call returns 1 but raises a DeprecationWarning.
Returning int(True) avoids the warning and makes the intended
type explicit.
$ python bool_return.py 1 ['DeprecationWarning'] 1
Best practices
A few rules keep integer conversion predictable:
- Return a real
int; floats and other types raiseTypeError. - Truncate towards zero when you want built-in
int()semantics, not floor division. - Implement
__index__as well if the object should work as a sequence index. - Do not rely on the
__index__fallback if__int__is defined but broken. - Return
int(value)rather than a bool to avoid a deprecation warning.
Source
object.__int__ - Python documentation
object.__index__ - Python documentation
math.trunc() - Python documentation
In this article we have implemented the __int__ method. We have
covered the conversion call, rounding, truncation versus floor division,
return-type errors, the difference from __index__, the fallback,
and packing structured values. For related topics, see Python
__index__ method, Python __float__
method, and Python round() function.
Author
List all Python tutorials.