Python __divmod__() Magic Method

Rate this post


object.__divmod__(self, other)

The Python __divmod__() method implements the built-in divmod operation. So, when you call divmod(a, b), Python attempts to call x.__divmod__(y). If the method is not implemented, Python first attempts to call __rdivmod__ on the right operand and if this isn’t implemented either, it raises a TypeError.

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.

Background Default divmod()

Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b). The first tuple value is the result of the integer division a//b. The second tuple is the result of the remainder, also called modulo operation a % b. In case of float inputs, divmod() still returns the division without remainder by rounding down to the next round number.

To understand this operation in detail, feel free to read over our tutorial or watch the following video:

Python divmod() — A Simple Guide

Example Custom divmod()

In the following example, you create a custom class Data and overwrite the __divmod__() method so that it returns a dummy string when trying to calculate the modulo of two numbers.

class Data:
    def __divmod__(self, other):
        return '... my result of divmod...'

a = Data()
b = Data()
c = divmod(a, b)

# ... my result of divmod...

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

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

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

class Data:

a = Data()
b = Data()
c = divmod(a, b)


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

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

The reason for this error is that the __divmod__() 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 divmod(), you need to provide the __divmod__(self, other) method in your class definition as shown previously:

class Data:
    def __divmod__(self, other):
        return '... my result of divmod...'

Of course, you’d use another return value in practice as explained in the “Background divmod()” section.

Python __divmod__ vs __rdivmod__

Say, you want to calculate the divmod of two custom objects x and y:

print(divmod(x, y))

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

  1. The method x.__divmod__() is not implemented in the first place, or
  2. The method x.__divmod__() 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.__rdivmod__() for reverse divmod on the right operand 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.__divmod__(x) instead of x.__divmod__(y), the result would be wrong because the divmod operation is non-commutative (neither the integer division, nor the modulo operation is commutative). That’s why y.__rdivmod__(x) is needed.

So, the difference between x.__divmod__(y) and x.__rdivmod__(y) is that the former calculates (x // y, x % y) whereas the latter calculates (y // x, y % x) — both calling the respective divmod method defined on object x.

You can see this in effect here where we attempt to call the divmod operation on the left operand x—but as it’s not implemented, Python simply calls the reverse divmod operation on the right operand y.

class Data_1:

class Data_2:
    def __rdivmod__(self, other):
        return 'called divmod'

x = Data_1()
y = Data_2()

print(divmod(x, y))
# called divmod


Explainer Video Modulo

You can also check out my explainer video where I’ll give you a deep dive on the built-in modulo operation and how to use them for various data types. Click to watch:

Python Modulo - A Simple Illustrated Guide

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!