Python __divmod__ Method
Last modified November 17, 2026 Python 3.15
The divmod(a, b) built-in returns the quotient and the remainder of
a division in a single call, and the special method behind it is
__divmod__. This article shows how the call is dispatched, how the
reflected hook works, what a custom numeric type should return, and how the
method relates to the // and % operators.
divmod() calls __divmod__
divmod(a, b) is evaluated as type(a).__divmod__(a, b).
For integers the result equals (a // b, a % b), so the pair
(q, r) satisfies b * q + r == a exactly. Unpacking the
pair into two names is the usual way to use it. With negative integers, Python
rounds the quotient toward negative infinity and gives the remainder the sign
of the divisor; the last three lines of the example verify the identity in each
case.
q, r = divmod(17, 5)
print(q, r)
print(divmod(17, 5) == (17 // 5, 17 % 5))
minutes, seconds = divmod(125, 60)
print(f"{minutes}m {seconds}s")
for a, b in [(10, -3), (-10, 3), (-10, -3)]:
q, r = divmod(a, b)
print(a, b, q, r, q * b + r)
Positive operands give the familiar result (3, 2), and 125 seconds
become two minutes and five seconds. For divmod(10, -3) the
quotient is -4 and the remainder is -2, which has the
sign of the divisor -3. For these integer operands, multiplying
back reconstructs the original dividend exactly.
$ python basic_divmod.py 3 2 True 2m 5s 10 -3 -4 -2 10 -10 3 -4 2 -10 -10 -3 3 -1 -10
Floating-point results
Floats implement the same protocol, but binary floating-point representation
can leak small errors into the remainder. The quotient is a float as well, even
when it is a whole number. These values are exactly what // and
% would return separately.
print(divmod(10.5, 3.2)) print(10.5 // 3.2, 10.5 % 3.2) print(divmod(1.0, 0.1)) print(divmod(7.5, 2)) a, b = 30.19, -85.51 q, r = divmod(a, b) print((q, r), b * q + r == a)
The remainder of 10.5 / 3.2 is not exactly 0.9, and
the remainder of 1.0 / 0.1 is not exactly 0.1. The
last line tests b * q + r == a and prints False. The
docs say q is usually math.floor(a / b) but may be
one less, and b * q + r can differ from a by a
rounding error. This is normal for binary floats; use
decimal.Decimal when exact decimal arithmetic matters.
$ python float_divmod.py (3.0, 0.8999999999999995) 3.0 0.8999999999999995 (9.0, 0.09999999999999995) (3.0, 1.5) (-1.0, -55.32000000000001) False
Implementing __divmod__
A custom numeric class implements the hook like any other special method. For
an operand it cannot handle, it returns the NotImplemented
singleton rather than raising NotImplementedError. That gives the
other operand a chance to handle the operation through its reflected method; if
neither does, the interpreter raises TypeError.
class MyNumber:
def __init__(self, value):
self.value = value
def __divmod__(self, other):
if not isinstance(other, MyNumber):
return NotImplemented
return divmod(self.value, other.value)
def __repr__(self):
return f"MyNumber({self.value})"
a = MyNumber(17)
b = MyNumber(5)
print(divmod(a, b))
try:
divmod(a, 5)
except TypeError as e:
print(type(e).__name__, e)
Two MyNumber instances produce a tuple of plain integers because
the hook delegates to the stored values. Mixing MyNumber with an
int reaches NotImplemented, and divmod(a, 5)
fails with the usual operand-type message.
$ python custom_divmod.py (3, 2) TypeError unsupported operand type(s) for divmod(): 'MyNumber' and 'int'
The reflected __rdivmod__ hook
When the left operand's __divmod__ returns
NotImplemented, Python tries type(b).__rdivmod__(b, a)
with the operands in reversed order. If the right operand's type is a proper
subclass of the left operand's type, the reflected method is tried first
instead. The example prints which method runs in each case.
class Left:
def __divmod__(self, other):
print("Left.__divmod__")
return NotImplemented
def __repr__(self):
return "Left()"
class Right:
def __rdivmod__(self, other):
print(f"Right.__rdivmod__ with {other!r}")
return (1, 2)
print(divmod(Left(), Right()))
class SubRight(Right, Left):
pass
print(divmod(Left(), SubRight()))
The first call runs Left.__divmod__, sees
NotImplemented, and then runs Right.__rdivmod__. In
the second call SubRight is a subclass of Left, so its
reflected method wins before Left.__divmod__ is consulted at all.
The reflected callback receives the left operand, which is why it can print
Left() as its argument.
$ python reflected_divmod.py Left.__divmod__ Right.__rdivmod__ with Left() (1, 2) Right.__rdivmod__ with Left() (1, 2)
The result does not have to be a tuple
The built-in returns exactly what the hook produces; it does not force a tuple or check the element types. A specialized result object can therefore carry extra meaning, at the cost of breaking code that expects to unpack the result. The tuple is a convention worth keeping for ordinary numeric types.
class DivModResult:
def __init__(self, quotient, remainder):
self.quotient = quotient
self.remainder = remainder
def __repr__(self):
return f"Result(q={self.quotient}, r={self.remainder})"
class MyNumber:
def __init__(self, value):
self.value = value
def __divmod__(self, other):
return DivModResult(*divmod(self.value, other.value))
result = divmod(MyNumber(17), MyNumber(5))
print(result)
print(type(result).__name__)
The unpacking happens inside the hook, where the tuple is still available, and
divmod() hands the resulting DivModResult back to the
caller unchanged. Code such as q, r = divmod(a, b) would now fail
unless the result object also supports iteration.
$ python custom_result.py Result(q=3, r=2) DivModResult
// and % are separate hooks
Implementing __divmod__ does not make an object work with
// or %. Those operators call
__floordiv__ and __mod__ directly, with no fallback to
the combined method, and the reverse is true as well.
class OnlyDivmod:
def __init__(self, value):
self.value = value
def __divmod__(self, other):
return divmod(self.value, other)
a = OnlyDivmod(17)
print("divmod:", divmod(a, 5))
try:
print("floordiv:", a // 5)
except TypeError as e:
print(type(e).__name__, e)
try:
print("mod:", a % 5)
except TypeError as e:
print(type(e).__name__, e)
Only the divmod() call succeeds. The operators raise
TypeError because the class defines neither
__floordiv__ nor __mod__.
$ python not_floordiv.py divmod: (3, 2) TypeError unsupported operand type(s) for //: 'OnlyDivmod' and 'int' TypeError unsupported operand type(s) for %: 'OnlyDivmod' and 'int'
Adding the missing operators
A numeric type that supports division should define __floordiv__
and __mod__ alongside __divmod__. The small class
below implements all three and delegates each one to the same stored value, so
the results are consistent.
class Number:
def __init__(self, value):
self.value = value
def __divmod__(self, other):
return divmod(self.value, other)
def __floordiv__(self, other):
return self.value // other
def __mod__(self, other):
return self.value % other
n = Number(17)
print(divmod(n, 5), n // 5, n % 5)
The three results agree because each method derives from the same pair of
values. If the operations are expensive, implement them through one shared
helper rather than making __floordiv__ and __mod__
call divmod(), which would compute both results and could recurse
if __divmod__ delegated back to the operators.
$ python all_three.py (3, 2) 3 2
Errors and special values
Division by zero raises ZeroDivisionError for both integers and
floats, and the hook can raise it directly. Complex numbers have no floor
division, so divmod() does not accept them. Other numeric types,
such as decimal.Decimal and fractions.Fraction,
implement the hook themselves and return numeric values.
try:
divmod(10, 0)
except ZeroDivisionError as e:
print(type(e).__name__, e)
try:
divmod(10.5, 0.0)
except ZeroDivisionError as e:
print(type(e).__name__, e)
try:
divmod(3 + 4j, 2)
except TypeError as e:
print(type(e).__name__, e)
Both the integer and float divisors produce the same message. The complex
operand is rejected because there is no ordering that would define a floor for
a complex quotient; the % operator fails for the same reason.
$ python divmod_errors.py ZeroDivisionError division by zero ZeroDivisionError division by zero TypeError unsupported operand type(s) for divmod(): 'complex' and 'int'
A practical use: formatting a duration
Repeated divmod() calls split a quantity into units of decreasing
size. Here a number of seconds is reduced to days, hours, minutes, and seconds,
and only the non-zero parts are shown. This pattern appears in countdowns,
log formatting, and human-readable time spans.
def format_duration(seconds):
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
parts = []
units = [(days, "d"), (hours, "h"), (minutes, "m"), (seconds, "s")]
for value, unit in units:
if value:
parts.append(f"{value}{unit}")
return " ".join(parts) or "0s"
for total in (0, 65, 3661, 90061):
print(total, format_duration(total))
Each step keeps the remainder for the next, smaller unit. Zero seconds fall
through to the explicit 0s fallback, while 90061 seconds become
one day, one hour, one minute, and one second.
$ python duration.py 0 0s 65 1m 5s 3661 1h 1m 1s 90061 1d 1h 1m 1s
Best practices
A numeric type that supports division should make the three related hooks behave the same way:
- Return
(quotient, remainder)in that order, following the built-in convention. - Return
NotImplementedfor unsupported operand types instead of raising an exception, so the reflected method can run. - Implement
__floordiv__and__mod__as well;//and%do not use__divmod__. - For exact types, keep the identity
b * q + r == atrue, and give the remainder the sign of the divisor; for floats, expect rounding. - Handle a zero divisor explicitly, raising
ZeroDivisionErrorlike the built-in types. - Use a tuple unless there is a clear reason for a custom result object, since callers often unpack the pair.
Source
object.__divmod__ - Python documentation
object.__rdivmod__ - Python documentation
divmod() - Python documentation
numbers - Python documentation
In this article we have implemented the __divmod__ method. We have
covered the built-in dispatch, floats, custom and reflected implementations,
custom result objects, the separate // and % hooks,
errors, and a duration formatter. For related topics, see
Python divmod() function,
Python __floordiv__ method,
Python __mod__ method, and
Python __add__ method.
Author
List all Python tutorials.