ZetCode

Python __ifloordiv__ Method

Last modified November 18, 2026 Python 3.15

The //= operator calls __ifloordiv__ on its left operand. A mutable object updates itself and returns self; an immutable one delegates to __floordiv__ and is rebound to the result. This article shows the dispatch, the fallback, floor semantics for negative values, validation, and a few complete implementations.

The //= dispatch

Evaluating a //= b calls type(a).__ifloordiv__(a, b) and binds the return value to a. The hook is looked up on the type, just like every other special method. The trace below shows one call per operation.

basic_ifloordiv.py
class Tally:
    def __init__(self, value):
        self.value = value

    def __ifloordiv__(self, other):
        print("__ifloordiv__", self.value, "//", other)
        self.value //= other
        return self

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


t = Tally(17)
t //= 5
t //= 2
print(t)

The first operation reduces 17 to 3, the second reduces 3 to 1. The method mutates self.value and returns the object, so the name t still refers to the same instance after both operations.

$ python basic_ifloordiv.py
__ifloordiv__ 17 // 5
__ifloordiv__ 3 // 2
Tally(1)

Fallback to __floordiv__

A class without __ifloordiv__ gets the same behaviour as a = a // b: Python calls __floordiv__ and rebinds the name. This is how immutable types handle //=.

fallback_floordiv.py
class Distance:
    def __init__(self, metres):
        self.metres = metres

    def __floordiv__(self, other):
        print("__floordiv__")
        return Distance(self.metres // other)

    def __repr__(self):
        return f"Distance({self.metres})"


d = Distance(17)
alias = d
d //= 5
print(d, alias, d is alias)

The regular floor-division method built a new Distance, so the alias keeps the original value and the identity test is False. Implement __floordiv__ alone when the object cannot be changed.

$ python fallback_floordiv.py
__floordiv__
Distance(3) Distance(17) False

Floor division is not truncation

Python's // rounds towards negative infinity, not towards zero. For negative operands that differs from converting a / b to an integer, and the in-place hook inherits the same rule.

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

    def __ifloordiv__(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, "int(a / 3) =", int(a / 3))

-7 // 3 is -3 because the result is floored, while int(-7 / 3) truncates towards zero and gives -2. The positive case is the same in both schemes. The identity a == (a // b) * b + a % b holds for every b.

$ python negative_floordiv.py
-7 -> Signed(-3) int(a / 3) = -2
7 -> Signed(2) int(a / 3) = 2

The operator.ifloordiv function

operator.ifloordiv(a, b) is the functional form of a //= b. It invokes the hook but, unlike the statement, cannot rebind the caller's variable.

operator_ifloordiv.py
import operator


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

    def __ifloordiv__(self, other):
        self.value //= other
        return self

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


t = Tally(17)
same = operator.ifloordiv(t, 5)
print(t, same, t is same)
print(operator.ifloordiv(17, 5))

The mutable Tally returns the object it changed, so both names refer to Tally(3). With plain integers the function returns a new value — 3 — which a caller would have to store explicitly.

$ python operator_ifloordiv.py
Tally(3) Tally(3) True
3

Mutating a collection in place

A container can divide each of its elements and still keep its identity. This list subclass updates its items one by one and returns self.

divisible_list.py
class Divisible(list):
    def __ifloordiv__(self, divisor):
        for i, item in enumerate(self):
            self[i] = item // divisor
        return self


nums = Divisible([10, 20, 33])
alias = nums
nums //= 4
print(nums, alias, nums is alias)

Every element is changed through item assignment, so the list object itself is never replaced and the alias sees the new values. A plain list has no __ifloordiv__; this subclass adds it without giving up normal list behaviour.

$ python divisible_list.py
[2, 5, 8] [2, 5, 8] True

Validating the divisor

The hook can reject operands before touching state. Returning NotImplemented lets Python try the other operand, while raising an error is appropriate for a value that is never valid, such as zero.

validate_ifloordiv.py
class SafeTally:
    def __init__(self, value):
        self.value = value

    def __ifloordiv__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        if other == 0:
            raise ValueError("divisor must not be zero")
        self.value //= other
        return self

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


s = SafeTally(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 raises a ValueError from the method. A float makes the method return NotImplemented; with no other hook to fall back to, Python raises TypeError. The final line shows that neither failure changed the stored value.

$ python validate_ifloordiv.py
SafeTally(3)
ValueError divisor must not be zero
TypeError unsupported operand type(s) for //=: 'SafeTally' and 'float'
SafeTally(3)

Declining an operand and the reflected method

When __ifloordiv__ returns NotImplemented, Python tries __floordiv__ on the left operand and then __rfloordiv__ on the right one. The result of that reflected method is what gets bound to the name.

reflected_ifloordiv.py
class Reflected:
    def __rfloordiv__(self, other):
        print("__rfloordiv__")
        return 99


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

    def __ifloordiv__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        self.value //= other
        return self

    def __floordiv__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        return Tally(self.value // other)

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


t = Tally(17)
t //= Reflected()
print(t)

The right operand supplied the answer, so t was rebound to the integer 99 rather than to a Tally. If you want reflected operations to keep your own type, implement the reflected hook to return an instance of that type instead.

$ python reflected_ifloordiv.py
__rfloordiv__
99

Best practices

Keep these points in mind when implementing in-place floor division:

Source

object.__ifloordiv__ - Python documentation

Emulating numeric types - Python documentation

operator.ifloordiv - Python documentation

In this article we have implemented the __ifloordiv__ method. We have covered the //= dispatch, the fallback to __floordiv__, negative operands, validation, and reflected operations. For related topics, see Python __floordiv__ method, Python __iadd__ method, and Python divmod() function.

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.