ZetCode

Python __mod__ Method

Last modified November 18, 2026 Python 3.15

The % operator calls __mod__ on its left operand. For numbers it computes a remainder; for strings the same operator means formatting. This article covers the call, Python's remainder rule for negative numbers, a circular index, custom formatting, the reflected and in-place variants, and the related divmod() function.

Basic modulo operation

A wrapper class can delegate the remainder to its stored value. Python's % result takes the sign of the divisor, which is worth showing explicitly because it differs from the C remainder rule.

basic_mod.py
class ModNumber:
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__")
        return self.value % other

    def __repr__(self):
        return f"ModNumber({self.value})"


number = ModNumber(17)
print(number % 5)
print(-7 % 3, 7 % -3, -7 % -3)

The hook printed its trace and returned 2. The built-in results show the sign rule: the remainder has the sign of the divisor. -7 % 3 is 2, while 7 % -3 is -2.

$ python basic_mod.py
__mod__
2
2 -2 -1

Circular indexing

Wrapping an index into a fixed range is a natural use of the remainder. A zero divisor should raise the usual ZeroDivisionError rather than being silently replaced by a made-up value.

circular_index.py
class CircularIndex:
    def __init__(self, position):
        self.position = position

    def __mod__(self, size):
        if size == 0:
            raise ZeroDivisionError("modulo by zero")
        return self.position % size

    def __repr__(self):
        return f"CircularIndex({self.position})"


index = CircularIndex(7)
print(index % 5, index % 3, CircularIndex(-1) % 5)
try:
    print(index % 0)
except ZeroDivisionError as e:
    print(type(e).__name__, e)

Position 7 wraps to 2 in a table of five slots and to 1 in a table of three. Position -1 wraps to 4 in a five-slot table, which is the last slot. A zero size is rejected just as it would be for a plain integer.

$ python circular_index.py
2 1 4
ZeroDivisionError modulo by zero

Custom formatting with %

Python's str already uses % for old-style formatting. A custom class can borrow that meaning; here a template object substitutes one placeholder with the right operand.

template_mod.py
class Template:
    def __init__(self, text):
        self.text = text

    def __mod__(self, value):
        return self.text.replace("%s", str(value))

    def __repr__(self):
        return f"Template({self.text!r})"


template = Template("The answer is %s")
print(template % 42)
print("built-in: ", "The answer is %s" % 42)

The custom hook produces the same text as the built-in string formatting for this simple case. Reusing an operator for a non-mathematical purpose is legal, but it should be documented because readers expect % to mean a remainder.

$ python template_mod.py
The answer is 42
built-in:  The answer is 42

The reflected __rmod__ method

If the left operand does not support the operation, Python tries __rmod__ on the right operand. This lets a custom object appear to the right of a built-in value.

reflected_mod.py
class Handler:
    def __rmod__(self, other):
        print("__rmod__")
        return f"Handled modulo: {other}"

    def __repr__(self):
        return "Handler()"


handler = Handler()
print(10 % handler)

The integer has no way to take a remainder with a Handler, so Python called handler.__rmod__(10). The returned string became the value of the expression.

$ python reflected_mod.py
__rmod__
Handled modulo: 10

In-place modulo

The %= operator calls __imod__ when available. A mutable object updates itself and returns self; the name is then bound to that return value.

imod.py
class Accumulator:
    def __init__(self, value):
        self.value = value

    def __imod__(self, other):
        print("__imod__")
        self.value %= other
        return self

    def __repr__(self):
        return f"Accumulator({self.value})"


acc = Accumulator(17)
alias = acc
acc %= 5
print(acc, alias, acc is alias)

Both names show the updated remainder and the identity test is True. Without __imod__, Python would fall back to __mod__ and rebind the name to a new object.

$ python imod.py
__imod__
Accumulator(2) Accumulator(2) True

Modulo and divmod

The divmod(a, b) function returns the quotient and remainder together. A class that wants both results efficiently can define __divmod__; otherwise divmod() uses __floordiv__ and __mod__.

divmod_mod.py
class Both:
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__")
        return self.value % other

    def __divmod__(self, other):
        print("__divmod__")
        return divmod(self.value, other)


b = Both(17)
print(b % 5)
print(divmod(b, 5))

The single % call used __mod__. divmod(b, 5) used the dedicated hook and returned the pair (3, 2). Defining both keeps the two operations independent.

$ python divmod_mod.py
__mod__
2
__divmod__
(3, 2)

The operator.mod function

operator.mod(a, b) and operator.imod(a, b) are functional forms of a % b and a %= b. They dispatch through the same hooks.

operator_mod.py
import operator


class Acc:
    def __init__(self, value):
        self.value = value

    def __imod__(self, other):
        self.value %= other
        return self

    def __repr__(self):
        return f"Acc({self.value})"


print(operator.mod(17, 5))
print(operator.imod(Acc(17), 5))

The plain integers return a new remainder. The mutable object is changed and returned, so operator.imod can be used wherever a callable form of %= is needed.

$ python operator_mod.py
2
Acc(2)

Best practices

A few rules keep % predictable:

Source

object.__mod__ - Python documentation

Binary arithmetic operations - Python documentation

divmod() - Python documentation

operator.mod - Python documentation

In this article we have implemented the __mod__ method. We have covered the % dispatch, the remainder sign rule, circular indexing, string formatting, reflected and in-place modulo, divmod() and operator.mod. For related topics, see Python __floordiv__ method, Python __imod__ method, and Python operators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.