ZetCode

Python __imod__ Method

Last modified November 18, 2026 Python 3.15

The %= operator calls __imod__ on its left operand. A mutable object reduces itself and returns self; otherwise Python falls back to __mod__. This article covers the dispatch, the sign rule for negative numbers, validation, and a few genuinely useful in-place modulo implementations.

The %= dispatch

a %= b is evaluated as a = type(a).__imod__(a, b). The hook receives both operands and its return value is bound back to the name. The trace below shows both calls.

basic_imod.py
class Counter:
    def __init__(self, value):
        self.value = value

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

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


c = Counter(17)
c %= 5
c %= 3
print(c)

The first operation leaves 2, and 2 % 3 is still 2. The method changes self.value and returns the object, so the name c keeps referring to the same instance. Returning anything else would silently rebind c.

$ python basic_imod.py
__imod__ 17 % 5
__imod__ 2 % 3
Counter(2)

Fallback to __mod__

Without __imod__, Python treats a %= b as a = a % b. The regular modulo hook creates a new object that is assigned back to the name.

fallback_mod.py
class Wrapped:
    def __init__(self, value):
        self.value = value

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

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


w = Wrapped(17)
alias = w
w %= 5
print(w, alias, w is alias)

The fallback produced a new Wrapped object, so the alias still holds the original value and w is alias is False. Built-in immutable types such as int and str follow this path; str uses % for old-style formatting rather than arithmetic.

$ python fallback_mod.py
__mod__
Wrapped(2) Wrapped(17) False

The sign of the remainder

Python's % always returns a result with the sign of the divisor, so a negative dividend still produces a non-negative remainder for a positive modulus. This differs from the C-style remainder, which has the sign of the dividend.

remainder_sign.py
class Signed:
    def __init__(self, value):
        self.value = value

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

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


for a in (-7, 7):
    x = Signed(a)
    x %= 3
    print(a, "->", x, " C-like remainder:", a - (int(a / 3) * 3))

-7 % 3 is 2, while the C-style remainder is -1. The identity a == (a // b) * b + a % b explains the difference: floor division and modulo are defined together. The in-place hook inherits the same rule because it delegates to %= on the stored integer.

$ python remainder_sign.py
-7 -> Signed(2)  C-like remainder: -1
7 -> Signed(1)  C-like remainder: 1

The operator.imod function

operator.imod(a, b) is the functional equivalent of a %= b. It calls the hook but cannot rebind the caller's variable.

operator_imod.py
import operator


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

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

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


c = Counter(17)
same = operator.imod(c, 5)
print(c, same, c is same)
print(operator.imod(17, 5))

For the mutable Counter the function returns the object it changed. With plain integers it returns a new value, which a caller must store explicitly — the function never writes back to a variable.

$ python operator_imod.py
Counter(2) Counter(2) True
2

A wrapping dial

Modulo is the natural operation for a value that wraps around at a fixed number of positions. Here %= reduces the dial to a smaller set of positions while keeping the current position valid.

wrapping_dial.py
class Dial:
    def __init__(self, position, positions):
        self.position = position % positions
        self.positions = positions

    def __imod__(self, divisor):
        if divisor <= 0:
            raise ValueError("divisor must be positive")
        self.position %= divisor
        self.positions = divisor
        return self

    def turn(self, steps):
        self.position = (self.position + steps) % self.positions
        return self

    def __repr__(self):
        return f"Dial({self.position}/{self.positions})"


d = Dial(9, 24)
d.turn(20)
print(d)
d %= 12
print(d)

Turning 20 steps from position 9 wraps to 5 on a 24-position dial. Reducing the dial to 12 positions leaves position 5 valid. The hook changes both attributes before returning self, so a second reference to the dial would see the new size too.

$ python wrapping_dial.py
Dial(5/24)
Dial(5/12)

Validating the modulus

A modulus of zero has no mathematical meaning, and a non-integer operand is usually a sign of a bug. Returning NotImplemented for the latter lets Python produce its standard TypeError.

validate_imod.py
class Safe:
    def __init__(self, value):
        self.value = value

    def __imod__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        if other == 0:
            raise ValueError("modulus must not be zero")
        self.value %= other
        return self

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


s = Safe(17)
s %= 5
print(s)
for bad in (0, 2.5):
    try:
        s %= bad
    except (ValueError, TypeError) as e:
        print(type(e).__name__, e)
print(s)

Zero is rejected with a ValueError from our own code. The float makes the hook return NotImplemented; since no other method can handle it, Python raises TypeError. The last line confirms both failures left the value unchanged.

$ python validate_imod.py
Safe(2)
ValueError modulus must not be zero
TypeError unsupported operand type(s) for %=: 'Safe' and 'float'
Safe(2)

Modulo and string formatting

Strings support % for old-style formatting and implement __mod__, so %= works on them through the fallback. A custom wrapper can implement __imod__ to make that explicit and keep its own state.

format_imod.py
s = "Result: %d"
s %= 42
print(s)


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

    def __imod__(self, values):
        self.text = self.text % values
        return self

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


t = Template("Hello %s, you have %d messages")
t %= ("Alice", 3)
print(t)

The plain string is rebound to the formatted result. The Template class updates its text attribute instead, which is useful when the template object is shared or stored in a collection. Both use the same % formatting rules.

$ python format_imod.py
Result: 42
Template('Hello Alice, you have 3 messages')

Best practices

Keep these points in mind when implementing in-place modulo:

Source

object.__imod__ - Python documentation

Emulating numeric types - Python documentation

operator.imod - Python documentation

Binary arithmetic operations - Python documentation

In this article we have implemented the __imod__ method. We have covered the %= dispatch, the fallback to __mod__, the sign of the remainder, validation, wrapping, and string formatting. For related topics, see Python __mod__ method, Python __ifloordiv__ method, and Python __divmod__ method.

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.