ZetCode

Python __ipow__ Method

Last modified November 18, 2026 Python 3.15

The **= operator calls __ipow__ on its left operand. A mutable object raises itself to the power and returns self; without the hook Python falls back to __pow__ and rebinds the name. This article explains both paths, the handling of unsupported exponents, and how modular exponentiation actually reaches the hooks.

The **= dispatch

Evaluating a **= b calls type(a).__ipow__(a, b) and binds the return value to a. The trace below shows one call per operation.

basic_ipow.py
class Number:
    def __init__(self, value):
        self.value = value

    def __ipow__(self, other):
        print("__ipow__", self.value, "**", other)
        self.value **= other
        return self

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


n = Number(2)
n **= 3
n **= 2
print(n)

The exponentiation is applied in sequence: 2 raised to 3 is 8, and 8 raised to 2 is 64. The method mutates self.value and returns the same object, so the name n is rebound to what it already referred to.

$ python basic_ipow.py
__ipow__ 2 ** 3
__ipow__ 8 ** 2
Number(64)

In-place means aliases see the change

A well-behaved hook updates an existing object, so every name pointing at it observes the new value. The identity test below confirms that no second object was made.

shared_ipow.py
class Power:
    def __init__(self, value):
        self.value = value

    def __ipow__(self, other):
        self.value **= other
        return self

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


p = Power(2)
alias = p
p **= 3
print(p, alias, p is alias)

Both names print Power(8) and p is alias is True. Returning a new object instead would leave the alias pointing at Power(2).

$ python shared_ipow.py
Power(8) Power(8) True

Fallback to __pow__

A class without __ipow__ gets a = a ** b when written with **=. The regular power hook builds a new object which is then assigned back to the name.

fallback_ipow.py
class PowOnly:
    def __init__(self, value):
        self.value = value

    def __pow__(self, other):
        print("__pow__")
        return PowOnly(self.value ** other)

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


p = PowOnly(2)
alias = p
p **= 3
print(p, alias, p is alias)

The fallback called __pow__ and rebound p. The alias is unchanged and the identity test is False. Implement __ipow__ only when mutating the existing object is both possible and desirable.

$ python fallback_ipow.py
__pow__
PowOnly(8) PowOnly(2) False

Validating the exponent

Check the operand before changing state. Unsupported types should return NotImplemented so Python can try the reflected operation, while an exponent that is invalid for the class can raise an exception.

validate_ipow.py
class Power:
    def __init__(self, value):
        self.value = value

    def __ipow__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        if other < 0:
            raise ValueError("exponent must not be negative")
        self.value **= other
        return self

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


x = Power(2)
x **= 4
print(x)
for bad in (-1, 1.5):
    try:
        y = Power(2)
        y **= bad
    except (ValueError, TypeError) as e:
        print(type(e).__name__, e)
print(x)

A negative exponent raises ValueError; a float makes the hook decline and Python raises TypeError. The final line shows that neither failure changed x.value.

$ python validate_ipow.py
Power(16)
ValueError exponent must not be negative
TypeError unsupported operand type(s) for **=: 'Power' and 'float'
Power(16)

Tuple exponents and three-argument pow()

A detail the old article confused: x **= (4, 10) passes the tuple as one argument to __ipow__. It does not mirror the three-argument pow() function, which never calls __ipow__ — it calls __pow__ with two arguments after the base.

modular_ipow.py
class ModNumber:
    def __init__(self, value):
        self.value = value

    def __ipow__(self, exponent):
        print("__ipow__ got", exponent)
        if isinstance(exponent, tuple):
            power, mod = exponent
            self.value = pow(self.value, power, mod)
        else:
            self.value **= exponent
        return self

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


x = ModNumber(3)
x **= 4
print(x)
y = ModNumber(3)
y **= (4, 10)
print(y)


class PowOnly:
    def __pow__(self, *args):
        print("__pow__ got", args)
        return self


p = PowOnly()
print(pow(p, 3, 5) is p)

The tuple exponent reaches __ipow__ as a single tuple, which the hook unpacks to compute pow(3, 4, 10) = 1. By contrast, pow(p, 3, 5) called __pow__ with the two arguments 3 and 5, and returned the same object. Keep the two mechanisms separate when documenting your class.

$ python modular_ipow.py
__ipow__ got 4
ModNumber(81)
__ipow__ got (4, 10)
ModNumber(1)
__pow__ got (3, 5)
True

Matrix powers

A matrix power is a good use of **=. Reusing __imatmul__ avoids allocating a fresh result matrix on every step of the loop.

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

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

    def __ipow__(self, power):
        if not isinstance(power, int) or power < 0:
            raise ValueError("non-negative integer required")
        result = Matrix([[1 if i == j else 0
                          for j in range(len(self.rows))]
                         for i in range(len(self.rows))])
        base = Matrix(self.rows)
        for _ in range(power):
            result @= base
        self.rows = result.rows
        return self

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


m = Matrix([[1, 1], [1, 0]])
m **= 5
print(m)

The fifth power of the Fibonacci transition matrix is [[8, 5], [5, 3]]. The identity matrix starts the product, and @= updates it in place five times. The original matrix is preserved as base, so each multiplication uses the same operand.

$ python matrix_ipow.py
Matrix([[8, 5], [5, 3]])

Declining an operand

Returning NotImplemented from __ipow__ lets Python try __pow__ and then the right operand's __rpow__. The value from the reflected method is what gets bound to the name.

reflected_ipow.py
class Reflected:
    def __rpow__(self, other):
        print("__rpow__")
        return 111


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

    def __ipow__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        self.value **= other
        return self

    def __pow__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        return Power(self.value ** other)

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


p = Power(2)
p **= Reflected()
print(p)

Both hooks on Power declined the Reflected object, so its __rpow__ supplied the answer. The name p was rebound to the integer 111, which is why returning NotImplemented rather than raising an error is important.

$ python reflected_ipow.py
__rpow__
111

The operator.ipow function

operator.ipow(a, b) is the functional form of a **= b. It calls the hook but does not rebind a variable in the caller's scope.

operator_ipow.py
import operator


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

    def __ipow__(self, other):
        self.value **= other
        return self

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


p = Power(2)
same = operator.ipow(p, 3)
print(p, same, p is same)
print(operator.ipow(2, 3))

The mutable object is returned after being changed, so both names refer to it. For an integer the function returns a new value, 8, which a caller must store explicitly.

$ python operator_ipow.py
Power(8) Power(8) True
8

Best practices

A few rules keep in-place exponentiation predictable:

Source

object.__ipow__ - Python documentation

Emulating numeric types - Python documentation

operator.ipow - Python documentation

pow() - Python documentation

In this article we have implemented the __ipow__ method. We have covered the **= dispatch, the fallback to __pow__, validation, tuple exponents, matrix powers, reflected operations, and operator.ipow. For related topics, see Python __pow__ method, Python __imul__ method, and Python pow() function.

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.