ZetCode

Python __pow__ Method

Last modified November 18, 2026 Python 3.15

The ** operator calls __pow__ with two arguments; the built-in pow(a, b, m) calls it with three when a modulus is given. A class can implement ordinary powers, modular exponentiation, reflected powers and domain-specific rules such as matrix exponentiation. This article demonstrates each of those forms with verified Python 3.15 examples.

Basic exponentiation

The hook receives the exponent and returns the result. It may accept any type it understands and return a plain number rather than an instance of the class.

basic_pow.py
class PowerNumber:
    def __init__(self, value):
        self.value = value

    def __pow__(self, exponent):
        print("__pow__ called")
        return self.value ** exponent

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


num = PowerNumber(3)
print(num ** 4)

The ** operator invoked the hook and the hook returned the integer 81. Printing the trace inside the implementation shows the call clearly; production code would simply return the value.

$ python basic_pow.py
__pow__ called
81

Two arguments versus three

The operator always passes two arguments to __pow__, while pow(a, b) does the same and pow(a, b, m) passes the modulus as a third argument. A hook that wants to support both must accept an optional third parameter.

arg_counts.py
class Probe:
    def __pow__(self, *args):
        print("args:", args)
        return 0


p = Probe()
print(p ** 2)
print(pow(p, 2))
print(pow(p, 2, 7))

Only the three-argument pow() supplied a modulus. A hook defined as __pow__(self, exponent) would raise TypeError on that call, which is why the modular example below declares modulus=None.

$ python arg_counts.py
args: (2,)
0
args: (2,)
0
args: (2, 7)
0

Modular exponentiation

Passing a modulus enables efficient modular exponentiation. The hook delegates to the three-argument built-in pow() with its stored value, avoiding a potentially enormous intermediate result.

modular_pow.py
class ModularNumber:
    def __init__(self, value):
        self.value = value

    def __pow__(self, exponent, modulus=None):
        if modulus is not None:
            print("with modulus", modulus)
            return pow(self.value, exponent, modulus)
        print("no modulus")
        return self.value ** exponent


num = ModularNumber(5)
print(num ** 3)
print(pow(num, 3, 7))

Without a modulus the result is 125. With modulus 7 it is 125 % 7 = 6. Checking is not None (rather than truth) matters because a modulus of zero has special meaning to pow().

$ python modular_pow.py
no modulus
125
with modulus 7
6

The reflected __rpow__ method

When the left operand cannot handle the power, Python calls __rpow__ on the right operand. The reflected hook receives the base as its argument.

rpow.py
class Square:
    def __rpow__(self, base):
        print("__rpow__ called with", base)
        return base ** 2


sq = Square()
print(5 ** sq)

The integer 5 does not know how to exponentiate by a Square, so Python called sq.__rpow__(5). The result 25 became the value of the expression.

$ python rpow.py
__rpow__ called with 5
25

Matrix exponentiation

A matrix can be raised to a non-negative integer power by repeated multiplication. Starting from the identity matrix makes the zeroth power correct, and negative exponents are rejected explicitly.

matrix_pow.py
class Matrix:
    def __init__(self, rows):
        self.rows = [list(row) for row in rows]

    def __mul__(self, other):
        return Matrix([
            [sum(a * b for a, b in zip(row, col))
             for col in zip(*other.rows)]
            for row in self.rows
        ])

    def __pow__(self, exponent):
        if not isinstance(exponent, int) or exponent < 0:
            raise ValueError("exponent must be a non-negative integer")
        n = len(self.rows)
        result = Matrix([[1 if i == j else 0 for j in range(n)]
                         for i in range(n)])
        for _ in range(exponent):
            result = result * self
        return result

    def __repr__(self):
        return f"Matrix({self.rows})"


m = Matrix([[1, 2], [3, 4]])
print(m ** 2)
print(m ** 0)
try:
    m ** -1
except ValueError as e:
    print(type(e).__name__, e)

Squaring the matrix gives the expected 2x2 product, the zeroth power is the identity matrix, and a negative exponent raises a clear error. Immutability is not required here because each multiplication builds a new matrix.

$ python matrix_pow.py
Matrix([[7, 10], [15, 22]])
Matrix([[1, 0], [0, 1]])
ValueError exponent must be a non-negative integer

Element-wise powers

A container can apply the exponent to each element. The hook can accept either a scalar exponent or another vector of the same length.

vector_pow.py
class Vector:
    def __init__(self, values):
        self.values = list(values)

    def __pow__(self, exponent):
        if isinstance(exponent, Vector):
            if len(self.values) != len(exponent.values):
                raise ValueError("vectors must have the same length")
            return Vector([a ** b for a, b in
                           zip(self.values, exponent.values)])
        return Vector([a ** exponent for a in self.values])

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


v = Vector([2, 3, 4])
print(v ** 2)
print(v ** Vector([1, 2, 3]))

The scalar form squares every component; the vector form uses matching exponents. Both return a new Vector and leave the original untouched.

$ python vector_pow.py
Vector([4, 9, 16])
Vector([2, 9, 64])

The operator.pow function

operator.pow(a, b) is the functional form of a ** b. It calls the same hook, including the reflected one when needed.

operator_pow.py
import operator


class PowerNumber:
    def __init__(self, value):
        self.value = value

    def __pow__(self, exponent):
        return self.value ** exponent

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


print(operator.pow(PowerNumber(2), 5))
print(operator.pow(3, 4))

The custom wrapper returned a plain integer, just as the built-in integers did. Both dispatched through their own implementations, and the functional form is useful for passing exponentiation as a callback.

$ python operator_pow.py
32
81

Best practices

A few rules keep ** predictable:

Source

object.__pow__ - Python documentation

pow() - Python documentation

The power operator - Python documentation

operator.pow - Python documentation

In this article we have implemented the __pow__ method. We have covered the two- and three-argument forms, modular exponentiation, reflected powers, matrix and vector examples, and operator.pow. For related topics, see Python __ipow__ method, Python __mul__ 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.