Python __truediv__() Magic Method

Syntax

object.__truediv__(self, other)

The Python __truediv__() method is called to implement the normal division operation / called true division—as opposed to the floor division operation //. For example to evaluate the expression x / y, Python attempts to call x.__truediv__(y).

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Example

In the following example, you create a custom class Data and overwrite the __truediv__() method so that it returns a dummy string when trying to divide two Data objects using the true division operation a / b.

class Data:
        
    def __truediv__(self, other):
        return '... my result of truediv...'


a = Data()
b = Data()
c = a / b

print(c)
# ... my result of truediv...

If you hadn’t defined the __truediv__() method, Python would’ve raised a TypeError.

How to Resolve TypeError: unsupported operand type(s) for /

Consider the following code snippet where you try to divide two custom objects without defining the dunder method __truediv__():

class Data:
    pass


a = Data()
b = Data()
c = a / b

print(c)

Running this leads to the following error message on my computer:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 7, in <module>
    c = a / b
TypeError: unsupported operand type(s) for /: 'Data' and 'Data'

The reason for this error is that the __truediv__() dunder method has never been defined—and it is not defined for a custom object by default. So, to resolve the TypeError: unsupported operand type(s) for /, you need to provide the __truediv__(self, other) method in your class definition as shown previously:

class Data:
        
    def __truediv__(self, other):
        return '... my result of truediv...'

Python __truediv__ vs __div__

  • The Python __truediv__() dunder method is called to implement the normal division operation in Python 3.
  • The Python __div__() dunder method is called to implement the normal division operation in Python 2. It doesn’t work in Python 3 anymore.

So, although both methods __truediv__ and __div__ have the same semantics as operators, they are different in that they are used for Python version 3 and 2, repsectively.

Python __truediv__ vs __rtruediv__

Say, you want to divide two objects x and y using true division:

print(x / y)

Python first tries to call the left object’s __truediv__() method x.__truediv__(y). But this may fail for two reasons:

  1. The method x.__truediv__() is not implemented in the first place, or
  2. The method x.__truediv__() is implemented but returns a NotImplemented value indicating that the data types are incompatible.

If this fails, Python tries to fix it by calling the y.__rtruediv__() for reverse true division on the right operator y. If this method is implemented, Python knows that it doesn’t run into a potential problem of a non-commutative operation. If it would just execute y.__truediv__(x) instead of x.__truediv__(y), it could cause an error if the operation is non-commutative. That’s why y.__rtruediv__(x) is needed which indicates that true division is possible after all.

So, the difference between x.__truediv__(y) and x.__rtruediv__(y) is that the former calculates x / y whereas the latter calculates y / x — both calling the respective true division method defined on object x.

References:

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:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!