Python __sub__ Method
Last modified November 18, 2026 Python 3.15
The expression a - b calls a.__sub__(b). If that
method returns NotImplemented, Python tries
b.__rsub__(a) before raising TypeError. Implementing
the hook lets a class define what subtraction means for its own values. This
article covers the basic pattern, vectors, mixed types with validation,
reflected and in-place variants, matrices and the operator.sub
function.
A basic subtraction
The method checks the operand type, computes the difference and returns a new
object. An unsupported type is reported with NotImplemented so
Python can look for a reflected implementation.
class Number:
def __init__(self, value):
self.value = value
def __sub__(self, other):
if isinstance(other, Number):
return Number(self.value - other.value)
return NotImplemented
print((Number(10) - Number(3)).value)
The original objects were left unchanged: the hook built a new
Number. Returning NotImplemented rather than raising
directly keeps the door open for __rsub__ on the other operand.
$ python basic.py 7
Vector subtraction
For a vector, subtraction is component-wise. A __repr__ makes the
result easy to read in the output.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
if isinstance(other, Vector):
return Vector(self.x - other.x, self.y - other.y)
return NotImplemented
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(5, 7) - Vector(3, 2))
Each coordinate was subtracted independently. Because the operands are the same type, no reflected call is needed.
$ python vector.py Vector(2, 5)
Mixed types and validation
An operand with a different type can be handled explicitly. Here a plain number is subtracted from the amount, while mixing currencies is rejected as meaningless.
class Currency:
def __init__(self, amount, code):
self.amount = amount
self.code = code
def __sub__(self, other):
if isinstance(other, Currency):
if self.code != other.code:
raise ValueError("different currencies")
return Currency(self.amount - other.amount, self.code)
if isinstance(other, (int, float)):
return Currency(self.amount - other, self.code)
return NotImplemented
def __repr__(self):
return f"{self.amount} {self.code}"
print(Currency(100, "USD") - Currency(30, "USD"))
print(Currency(100, "USD") - 15)
try:
Currency(100, "USD") - Currency(30, "EUR")
except ValueError as e:
print(type(e).__name__, e)
The two valid operations produced new amounts; the mismatched currencies
raised ValueError. Validation belongs in the hook so an invalid
difference can never be produced.
$ python currency.py 70 USD 85 USD ValueError different currencies
Reflected subtraction
Subtraction is not commutative, so the reflected method must reverse the
operands. Python calls __rsub__(self, other) with the left operand
as other.
class Temperature:
def __init__(self, value):
self.value = value
def __sub__(self, other):
if isinstance(other, Temperature):
return Temperature(self.value - other.value)
return NotImplemented
def __rsub__(self, other):
if isinstance(other, (int, float)):
return Temperature(other - self.value)
return NotImplemented
def __repr__(self):
return f"{self.value}C"
print(Temperature(10) - Temperature(3))
print(20 - Temperature(10))
The first line used __sub__; the second used
__rsub__ and computed 20 - 10. Forgetting to reverse
the operands is the most common mistake in a reflected arithmetic method.
$ python rsub.py 7C 10C
In-place subtraction
The -= operator calls __isub__. Returning
self keeps aliases pointing at the mutated object, which is the
behaviour of built-in mutable containers.
class Account:
def __init__(self, balance):
self.balance = balance
def __sub__(self, other):
if isinstance(other, (int, float)):
return Account(self.balance - other)
return NotImplemented
def __isub__(self, other):
if isinstance(other, (int, float)):
self.balance -= other
return self
return NotImplemented
def __repr__(self):
return f"Account(balance={self.balance})"
account = Account(100)
alias = account
account -= 30
print(account, "alias is account:", alias is account)
other = Account(100)
original = other
other = other - 30
print(other, "same object:", other is original)
After -= the alias still referred to the same, now smaller,
account. Plain - returned a separate object, so the name was
rebound and the old object was untouched.
$ python isub.py Account(balance=70) alias is account: True Account(balance=70) same object: False
Matrix differences
A two-dimensional container can subtract element by element and check that
the shapes match. A shape mismatch is a real error, not a case for
NotImplemented.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __sub__(self, other):
if not isinstance(other, Matrix):
return NotImplemented
same_shape = (len(self.rows) == len(other.rows)
and all(len(a) == len(b)
for a, b in zip(self.rows, other.rows)))
if not same_shape:
raise ValueError("matrices must have the same shape")
return Matrix([[a - b for a, b in zip(ra, rb)]
for ra, rb in zip(self.rows, other.rows)])
def __repr__(self):
return f"Matrix({self.rows})"
a = Matrix([[5, 7], [9, 11]])
b = Matrix([[1, 2], [3, 4]])
print(a - b)
try:
a - Matrix([[1, 2], [3, 4], [5, 6]])
except ValueError as e:
print(type(e).__name__, e)
Matching matrices were subtracted cell by cell; a different number of rows
raised ValueError. Returning NotImplemented here
would only hide a genuine mistake.
$ python matrix.py Matrix([[4, 5], [6, 7]]) ValueError matrices must have the same shape
When neither side can subtract
If both __sub__ and __rsub__ return
NotImplemented, Python raises TypeError. The
operator module exposes the same operation as a function.
import operator
class Opaque:
pass
try:
Opaque() - Opaque()
except TypeError as e:
print(type(e).__name__, e)
class Number:
def __init__(self, value):
self.value = value
def __sub__(self, other):
if isinstance(other, Number):
return Number(self.value - other.value)
return NotImplemented
print(operator.sub(Number(9), Number(2)).value)
The first error came from Python after both hooks declined the operation.
operator.sub(a, b) is exactly equivalent to a - b,
which is handy when a function is needed as a callback.
$ python not_implemented.py TypeError unsupported operand type(s) for -: 'Opaque' and 'Opaque' 7
Best practices
A few rules keep __sub__ predictable:
- Return
NotImplementedfor unknown operand types so the reflected method gets a chance. - Reverse the operands inside
__rsub__— subtraction is not commutative. - Return a new object from
__sub__and mutate in__isub__only. - Validate units and shapes before computing a difference.
- Keep
operator.subin mind when passing arithmetic as a function argument.
Source
object.__sub__ - Python documentation
operator.sub - Python documentation
Emulating numeric types - Python documentation
In this article we have implemented the __sub__ method. We have
covered the operator dispatch, vectors, mixed types, validation, reflected and
in-place subtraction, matrices and operator.sub. For related
topics, see Python __rsub__ method,
Python __isub__ method, and
Python operators.
Author
List all Python tutorials.