__pow__() method implements the built-in exponentiation operation. So, when you call
pow(a, b) or
a ** b, Python attempts to call
x.__pow__(y). If the method is not implemented, Python first attempts to call
__rpow__ on the right operand and if this isn’t implemented either, it raises a
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 pow()
The double asterisk (**) symbol is used as an exponentiation operator. The left operand is the base and the right operand is the power. For example, the expression
x**n multiplies the value
x with itself,
To understand this operation in detail, feel free to read over our tutorial or watch the following video:
Example Custom __pow__()
In the following example, you create a custom class
Data and overwrite the
__pow__() method so that it returns a dummy string when trying to calculate the power of two numbers.
class Data: def __pow__(self, other): return '... my result of expoentiation...' a = Data() b = Data() print(pow(a, b)) # ... my result of exponentiation... print(a ** b) # ... my result of exponentiation...
If you hadn’t defined the
__pow__() method, Python would’ve raised a
TypeError: unsupported operand type(s) for ** or pow()
Consider the following code snippet where you try to calculate the exponent of two custom objects without defining the dunder method
class Data: pass a = Data() b = Data() print(pow(a, b)) # ... my result of exponentiation... print(a ** b) # ... my result of exponentiation...
Running this leads to the following error message on my computer:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 8, in <module> print(pow(a, b)) TypeError: unsupported operand type(s) for ** or pow(): 'Data' and 'Data'
The reason for this error is that the
__pow__() 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 ** or pow(), you need to provide the
__pow__(self, other) method in your class definition as shown previously:
class Data: def __pow__(self, other): return '... my result of expoentiation...'
Of course, you’d use another return value in practice as explained in the “Background pow()” section.
Python __pow__ Modulo
The third argument of the
__pow__ method is the
mod argument. If present, it calculates the base (first argument) to the power of the exponent (second argument) modulo the third argument. Semantically,
__pow(x, y, mod)__ calculates
(x ** y) % mod but it is much faster because of modular exponentiation that avoids calculating
x ** y as an intermediate result.
The following experiment shows that
pow(x, y, mod) can be more than twice as fast than
(x**y) % mod:
import time x, y, mod = 999, 888, 44 start = time.time() print((x ** y) % mod) stop = time.time() print('Elapsed time for (x ** y) % mod:', stop - start) start = time.time() print(pow(x, y, mod)) stop = time.time() print('Elapsed time for pow(x, y, mod):', stop - start)
25 Elapsed time for (x ** y) % mod: 0.026185274124145508 25 Elapsed time for pow(x, y, mod): 0.009267568588256836
To overwrite the
__pow__() method with the third modulo argument, simply add the third argument like so:
class Data: def __pow__(self, other, modulo): return (self, other, modulo) x, y, m = Data(), Data(), Data() print(pow(x, y, m)) # (<__main__.Data object at 0x0000015EC6C86FA0>, <__main__.Data object at 0x0000015EC89FD4F0>, <__main__.Data object at 0x0000015EC8A570A0>)
You can see that the built-in
pow() method internally calls
Data.__pow__() on the three provided arguments. The result is a tuple of object references of type
Python __pow__ vs __rpow__
Say, you want to calculate the exponent of two custom objects
print(x ** y)
Python first tries to call the left object’s
x.__pow__(y). But this may fail for two reasons:
- The method
x.__pow__()is not implemented in the first place, or
- The method
x.__pow__()is implemented but returns a
NotImplementedvalue indicating that the data types are incompatible.
If this fails, Python tries to fix it by calling the
y.__rpow__() for reverse power on the right operand
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.__pow__(x) instead of
x.__pow__(y), the result would be wrong because the exponentiation operation may be non-commutative when custom defined. That’s why
y.__rpow__(x) is needed.
So, the difference between
x.__rpow__(y) is that the former calculates
x ** y whereas the latter calculates
y ** x — both calling the respective exponentiation method defined on object
You can see this in effect here where we attempt to call the exponentiation operation on the left operand
x—but as it’s not implemented, Python simply calls the reverse exponentiation operation on the right operand
class Data_1: pass class Data_2: def __rpow__(self, other): return 'called exponentiation' x = Data_1() y = Data_2() print(x ** y) # called exponentiation
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.