Python __itruediv__ Method
Last modified November 18, 2026 Python 3.15
The /= operator calls __itruediv__ on its left
operand. A mutable object divides itself and returns self;
otherwise Python falls back to __truediv__. Unlike floor
division, true division always produces a float for built-in numbers. This
article covers the dispatch, validation, exact rational arithmetic, and the
reflected operation.
The /= dispatch
Evaluating a /= b calls
type(a).__itruediv__(a, b) and binds the return value to
a. The example also keeps an alias to show that the object was
changed rather than replaced.
class Number:
def __init__(self, value):
self.value = value
def __itruediv__(self, other):
print("__itruediv__")
self.value /= other
return self
def __repr__(self):
return f"Number({self.value!r})"
n = Number(10)
alias = n
n /= 4
print(n, alias, n is alias, type(n.value).__name__)
The hook divided 10 by 4 and returned the same object, so the alias sees
2.5 too. The type of n.value is float: true division
never returns an integer, even when both operands were integers.
$ python basic_itruediv.py __itruediv__ Number(2.5) Number(2.5) True float
Fallback to __truediv__
A class without __itruediv__ gets
a = a / b when written with /=. The regular
division hook creates a new object and the name is rebound to it.
class Frozen:
def __init__(self, value):
self.value = value
def __truediv__(self, other):
print("__truediv__")
return Frozen(self.value / other)
def __repr__(self):
return f"Frozen({self.value})"
f = Frozen(10)
alias = f
f /= 4
print(f, alias, f is alias)
The fallback built a new Frozen object. The alias keeps the
original value and the identity test is False. Immutable types
should implement __truediv__ only.
$ python fallback_itruediv.py __truediv__ Frozen(2.5) Frozen(10) False
Exact rational division
A ratio class can avoid floating-point error by normalizing its numerator
and denominator with fractions.Fraction after every operation.
The in-place hook still updates and returns self.
from fractions import Fraction
class Ratio:
def __init__(self, numerator, denominator=1):
self.numerator = numerator
self.denominator = denominator
def _normalize(self):
value = Fraction(self.numerator, self.denominator)
self.numerator = value.numerator
self.denominator = value.denominator
def __itruediv__(self, other):
if isinstance(other, Ratio):
self.numerator *= other.denominator
self.denominator *= other.numerator
else:
self.denominator *= other
self._normalize()
return self
def __repr__(self):
return f"Ratio({self.numerator}/{self.denominator})"
r = Ratio(3, 4)
r /= Ratio(1, 2)
print(r)
r /= 3
print(r)
Dividing by 1/2 doubles the ratio to 3/2, and dividing that by 3 gives
1/2. Fraction cancels common factors automatically, so the
object never stores an unreduced pair such as 6/4.
$ python ratio_itruediv.py Ratio(3/2) Ratio(1/2)
Validating the divisor
An unsupported divisor can be declined with
NotImplemented, while zero should raise before any state
changes. This keeps a rejected division from corrupting the object.
class Vec:
def __init__(self, *components):
self.components = list(components)
def __itruediv__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
if scalar == 0:
raise ValueError("division by zero")
self.components = [x / scalar for x in self.components]
return self
def __repr__(self):
return f"Vec({self.components})"
v = Vec(2, 4, 6)
v /= 2
print(v)
for bad in (0, "x"):
try:
w = Vec(2, 4)
w /= bad
except (ValueError, TypeError) as e:
print(type(e).__name__, e)
print(v)
Zero is rejected with ValueError from our own code. The
string makes the hook return NotImplemented, and Python raises
TypeError. The final line confirms v was not
affected by either failed attempt.
$ python validate_itruediv.py Vec([1.0, 2.0, 3.0]) ValueError division by zero TypeError unsupported operand type(s) for /=: 'Vec' and 'str' Vec([1.0, 2.0, 3.0])
Element-wise matrix division
A matrix can divide each element by a scalar without replacing the matrix object. Rebuilding the rows with a comprehension also avoids accidentally sharing nested lists.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __itruediv__(self, other):
if not isinstance(other, (int, float)):
return NotImplemented
self.rows = [[x / other for x in row]
for row in self.rows]
return self
def __repr__(self):
return "\n".join(" ".join(map(str, row))
for row in self.rows)
m = Matrix([[1, 2], [3, 4]])
m /= 2
print(m)
Every entry is divided by 2 and printed as a float. The matrix object itself is unchanged, so another name referring to it would show the same rows. Note that the hook is still responsible for handling a zero divisor — this simplified version only demonstrates the element-wise update.
$ python matrix_itruediv.py 0.5 1.0 1.5 2.0
Declining an operand
When both hooks on the left operand decline, Python tries the right
operand's __rtruediv__. Its return value is bound to the name,
even if that means the name no longer refers to the original type.
class Reflected:
def __rtruediv__(self, other):
print("__rtruediv__")
return 222
class Number:
def __init__(self, value):
self.value = value
def __itruediv__(self, other):
if not isinstance(other, int):
return NotImplemented
self.value /= other
return self
def __truediv__(self, other):
if not isinstance(other, int):
return NotImplemented
return Number(self.value / other)
def __repr__(self):
return f"Number({self.value})"
n = Number(10)
n /= Reflected()
print(n)
The Reflected object supplied the result, so n
was rebound to the integer 222. Returning NotImplemented from
the left hooks is what gives the other operand a chance to answer.
$ python reflected_itruediv.py __rtruediv__ 222
The operator.itruediv function
operator.itruediv(a, b) is the functional form of
a /= b. It calls the hook but cannot rebind the caller's
variable.
import operator
class Number:
def __init__(self, value):
self.value = value
def __itruediv__(self, other):
self.value /= other
return self
def __repr__(self):
return f"Number({self.value!r})"
n = Number(10)
same = operator.itruediv(n, 4)
print(n, same, n is same)
print(operator.itruediv(10, 4))
The mutable object is returned after being changed, so both names refer to it. For plain integers the function returns a new float, 2.5, which the caller must store explicitly.
$ python operator_itruediv.py Number(2.5) Number(2.5) True 2.5
Best practices
A few rules keep in-place true division predictable:
- Return
selfafter mutating a mutable object; the operator binds the return value. - Implement
__truediv__too so/and the fallback path work. - Expect a float result for true division, even from integer operands.
- Return
NotImplementedfor unsupported types and validate zero before changing state. - Use
fractions.Fractionwhen exact rational results matter.
Source
object.__itruediv__ - Python documentation
Emulating numeric types - Python documentation
operator.itruediv - Python documentation
fractions - Python documentation
In this article we have implemented the __itruediv__ method.
We have covered the /= dispatch, the fallback to
__truediv__, float results, exact ratios, validation, matrix
division, reflected operations, and operator.itruediv. For
related topics, see Python __truediv__
method, Python __ifloordiv__
method, and Python fractions
module.
Author
List all Python tutorials.