ZetCode

Python __isub__ Method

Last modified November 18, 2026 Python 3.15

The -= operator calls __isub__ on its left operand. A mutable object subtracts in place and returns self; without the hook Python falls back to __sub__. This article covers both paths, validation, reflected operations, and a correction to a common misconception: lists do not support -= at all.

The -= dispatch

Evaluating a -= b calls type(a).__isub__(a, b) and binds the return value to a. The trace below shows the hook being called once.

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

    def __isub__(self, other):
        print("__isub__", self.value, "-", other)
        self.value -= other
        return self

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


c = Counter(10)
c -= 3
print(c)

The method changed self.value to 7 and returned the object. Returning something else — even None by mistake — would rebind c to that value instead.

$ python basic_isub.py
__isub__ 10 - 3
Counter(7)

Aliases observe an in-place change

Mutating the existing object means all references to it see the new state. This is the practical difference from the fallback path, which creates a new object.

shared_isub.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __isub__(self, other):
        self.x -= other.x
        self.y -= other.y
        return self

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v = Vector(5, 7)
alias = v
v -= Vector(2, 3)
print(v, alias, v is alias)

Both names refer to Vector(3, 4) and v is alias is True. Component-wise subtraction is a natural definition for this type, and no temporary vector is built.

$ python shared_isub.py
Vector(3, 4) Vector(3, 4) True

Fallback to __sub__

Without __isub__, Python evaluates a -= b as a = a - b. The regular subtraction hook builds a new object and the name is rebound to it.

fallback_isub.py
class Frozen:
    def __init__(self, value):
        self.value = value

    def __sub__(self, other):
        print("__sub__")
        return Frozen(self.value - other)

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


f = Frozen(10)
alias = f
f -= 3
print(f, alias, f is alias)

The alias keeps the original value and the identity test is False. Immutable types should implement __sub__ only, since they cannot update themselves.

$ python fallback_isub.py
__sub__
Frozen(7) Frozen(10) False

Validating the operand

The hook can enforce domain rules before it changes any state. Here a subtraction between two measurements is allowed only when their units match.

units_isub.py
class Measurement:
    def __init__(self, amount, unit="m"):
        self.amount = amount
        self.unit = unit

    def __isub__(self, other):
        if isinstance(other, Measurement):
            if other.unit != self.unit:
                raise ValueError("unit mismatch")
            other = other.amount
        if not isinstance(other, (int, float)):
            return NotImplemented
        self.amount -= other
        return self

    def __repr__(self):
        return f"{self.amount}{self.unit}"


m = Measurement(10)
m -= 2.5
print(m)
m -= Measurement(1, "m")
print(m)
try:
    m -= Measurement(1, "cm")
except ValueError as e:
    print(type(e).__name__, e)

A plain number and a measurement in the same unit are accepted. The mismatched unit raises before self.amount is touched, so the object still holds 6.5 metres after the failed operation.

$ python units_isub.py
7.5m
6.5m
ValueError unit mismatch

Lists do not support -=

A frequent misconception is that -= extends a list, the way += does. It does not: list defines neither __isub__ nor __sub__, so the operation raises TypeError. Sets, on the other hand, implement __isub__ as difference_update.

builtin_isub.py
numbers = [1, 2, 3]
try:
    numbers -= [1]
except TypeError as e:
    print(type(e).__name__, e)
print(numbers)

s = {1, 2, 3, 4, 5}
s -= {3, 4}
print(s)

The list is unchanged after the failed operation. To remove elements use remove, discard or a list comprehension; to append use += or extend. The set lost 3 and 4 through its own in-place hook.

$ python builtin_isub.py
TypeError unsupported operand type(s) for -=: 'list' and 'list'
[1, 2, 3]
{1, 2, 5}

Declining an operand

Returning NotImplemented asks Python to try the reflected operation. If the right operand implements __rsub__, its result is bound to the name.

reflected_isub.py
class Reflected:
    def __rsub__(self, other):
        print("__rsub__")
        return 100


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

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

    def __sub__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        return Left(self.value - other)

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


x = Left(10)
x -= Reflected()
print(x)

Both hooks on Left declined, so Reflected.__rsub__ ran and returned 100. The name x was rebound to that integer, not to a Left instance. This is why declining an operand should be explicit rather than raising an exception from the hook.

$ python reflected_isub.py
__rsub__
100

The operator.isub function

operator.isub(a, b) calls __isub__ without rebinding a variable in the caller's scope. For a mutable operand it returns the object it changed.

operator_isub.py
import operator


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

    def __isub__(self, other):
        self.value -= other
        return self

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


c = Counter(10)
same = operator.isub(c, 3)
print(c, same, c is same)
print(operator.isub(10, 3))

The Counter was mutated and returned, so both names refer to it. With plain integers the function returns a new value, 7, that the caller would need to store explicitly.

$ python operator_isub.py
Counter(7) Counter(7) True
7

Best practices

A few rules keep in-place subtraction predictable:

Source

object.__isub__ - Python documentation

Emulating numeric types - Python documentation

operator.isub - Python documentation

Set operations - Python documentation

In this article we have implemented the __isub__ method. We have covered the -= dispatch, aliases, the fallback to __sub__, validation, the behaviour of built-in lists and sets, reflected operations, and operator.isub. For related topics, see Python __sub__ method, Python __iadd__ method, and Python set difference.

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.