ZetCode

Python __truediv__ Method

Last modified November 18, 2026 Python 3.15

The expression a / b calls a.__truediv__(b), the implementation of true division. Since Python 3, dividing integers with / returns a float, and a class can define its own meaning for the operator. This article shows fraction division with normalization, mixed operand types, reflected and in-place division, division-by-zero handling, element-wise vector division and the operator.truediv function.

Dividing fractions

A fraction divides by multiplying by the reciprocal. Reducing the result in the constructor keeps the representation canonical, so equal values print the same way.

fractions.py
import math


class Fraction:
    def __init__(self, numerator, denominator):
        divisor = math.gcd(numerator, denominator)
        self.numerator = numerator // divisor
        self.denominator = denominator // divisor

    def __truediv__(self, other):
        if not isinstance(other, Fraction):
            return NotImplemented
        return Fraction(self.numerator * other.denominator,
                        self.denominator * other.numerator)

    def __repr__(self):
        return f"Fraction({self.numerator}, {self.denominator})"


print(Fraction(1, 2) / Fraction(3, 4))

The unreduced product would have been Fraction(4, 6); the constructor divided both parts by their greatest common divisor. This is a small example — fractions.Fraction in the standard library is the production-quality version.

$ python fractions.py
Fraction(2, 3)

Mixed operand types

The method can give different results for different operand types: dividing two distances yields a plain ratio, while dividing a distance by a number yields another distance.

distances.py
class Distance:
    def __init__(self, meters):
        self.meters = meters

    def __truediv__(self, other):
        if isinstance(other, Distance):
            return self.meters / other.meters
        if isinstance(other, (int, float)):
            return Distance(self.meters / other)
        return NotImplemented

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


print(Distance(100) / Distance(20))
print(Distance(100) / 4)

A ratio has no unit and is returned as a float; a scalar division keeps the unit, so a new Distance is produced. Returning a different type for each case is legitimate as long as the meaning is clear.

$ python distances.py
5.0
Distance(25.0)

Reflected division

When the left operand does not support the operation, Python calls __rtruediv__ on the right operand with the operands reversed. This is how a custom type can work on the right of a built-in number.

rtruediv.py
class SpecialNumber:
    def __init__(self, value):
        self.value = value

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

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


print(10 / SpecialNumber(5))

int.__truediv__ did not know how to divide by SpecialNumber, so Python called __rtruediv__, which computed 10 / 5. A subclass on the right gets a chance before a strictly unrelated type.

$ python rtruediv.py
2.0

In-place division

The /= operator calls __itruediv__. Returning self preserves aliases and avoids allocating a second object.

itruediv.py
class Accumulator:
    def __init__(self, value):
        self.value = value

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

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


acc = Accumulator(100)
alias = acc
acc /= 4
print(acc, "alias is acc:", alias is acc)

The single object changed in place and the alias still pointed at it. Note that dividing an integer attribute with /= produced a float, just as ordinary true division does.

$ python itruediv.py
Accumulator(25.0) alias is acc: True

Handling division by zero

A class can raise a clearer error than the default one, but checking for zero explicitly is important. Letting Python raise ZeroDivisionError itself is usually simpler.

zero.py
class SafeDivider:
    def __init__(self, value):
        self.value = value

    def __truediv__(self, other):
        if isinstance(other, SafeDivider):
            return SafeDivider(self.value / other.value)
        if isinstance(other, (int, float)):
            if other == 0:
                raise ZeroDivisionError("cannot divide by zero")
            return SafeDivider(self.value / other)
        return NotImplemented

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


print(SafeDivider(10) / SafeDivider(2))
try:
    SafeDivider(10) / 0
except ZeroDivisionError as e:
    print(type(e).__name__, e)

The valid division succeeded and the zero divisor produced a descriptive error. The old version of this example raised ValueError and left the failing call commented out, so the error path was never demonstrated.

$ python zero.py
SafeDivider(5.0)
ZeroDivisionError cannot divide by zero

Element-wise vector division

A vector can be divided by a scalar or by another vector. Each branch checks its operand and the zero case before computing new components.

vector.py
class Vector:
    def __init__(self, *parts):
        self.parts = list(parts)

    def __truediv__(self, other):
        if isinstance(other, (int, float)):
            if other == 0:
                raise ZeroDivisionError("cannot divide by zero")
            return Vector(*(part / other for part in self.parts))
        if isinstance(other, Vector):
            return Vector(*(a / b for a, b in zip(self.parts, other.parts)))
        return NotImplemented

    def __repr__(self):
        return f"Vector({self.parts})"


print(Vector(10, 20, 30) / 2)
print(Vector(10, 20, 30) / Vector(2, 4, 5))

Both calls returned new vectors with float components. Dividing by another vector pairs the components by position, so the two operands must have the same length in real code.

$ python vector.py
Vector([5.0, 10.0, 15.0])
Vector([5.0, 5.0, 6.0])

When neither side can divide

If both operands decline the operation, Python raises a TypeError. The operator.truediv function calls the same hook and is useful as a callback.

operator_div.py
import operator


class Opaque:
    pass


try:
    Opaque() / Opaque()
except TypeError as e:
    print(type(e).__name__, e)


class Distance:
    def __init__(self, meters):
        self.meters = meters

    def __truediv__(self, other):
        if isinstance(other, (int, float)):
            return Distance(self.meters / other)
        return NotImplemented

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


print(operator.truediv(Distance(10), 2))

The first error shows that both hooks returned NotImplemented. operator.truediv(a, b) is equivalent to a / b, including the reflected-method dispatch.

$ python operator_div.py
TypeError unsupported operand type(s) for /: 'Opaque' and 'Opaque'
Distance(5.0)

Best practices

A few rules keep __truediv__ predictable:

Source

object.__truediv__ - Python documentation

operator.truediv - Python documentation

fractions - Python documentation

In this article we have implemented the __truediv__ method. We have covered fraction division, mixed types, reflected and in-place operators, zero handling, element-wise division and operator.truediv. For related topics, see Python __floordiv__ method, Python __rtruediv__ method, and Python operators.

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.