Python __div__() Magic Method

The Python __div__() magic method overrides the division operation for a custom object in Python 2.

In Python 3, it was replaced by the __truediv__() for a / b and __floordiv__() dunder methods for a // b.

  • The Python __truediv__() method is called to implement the normal division operation / called true division. For example to evaluate the expression x / y, Python attempts to call x.__truediv__(y).
  • The Python __floordiv__() method implements the integer division operation // called floor division. For example to evaluate the expression x // y, Python attempts to call x.__floordiv__(y).

If the method is not implemented, Python first attempts to call __rtruediv__ or __rfloordiv__ on the right operand and if this isn’t implemented either, it raises a TypeError.

TypeError: unsupported operand type(s) for /

In the following example, you try to override the division operator on the custom object Data by using the __div__() magic method.

# Python 3 - WRONG:
class Data:
    def __div__(self, other):
        return 42.42


x = Data()
y = Data()

print(x / y)

However, this doesn’t work for Python 3—you obtain the following output error message:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 9, in <module>
    print(x / y)
TypeError: unsupported operand type(s) for /: 'Data' and 'Data'

To fix this issue, override the __truediv__() magic method for Python 3 instead of the __div__() magic method for Python 2 to define the true division operator x / y.

You can see how it’s done in the following code example (see highlighted lines):

class Data:
    def __truediv__(self, other):
        return 42.42


x = Data()
y = Data()

print(x / y)
# 42.42

Explainer Video Division Operators

You can also check out my explainer video where I’ll give you a deep dive on the integer and true division operators and how to use them for various data types. Click to watch: