ZetCode

Python __imul__ Method

Last modified November 18, 2026 Python 3.15

The *= operator calls __imul__ on its left operand. Mutable objects change in place and return self; immutable ones fall back to __mul__. This article shows the dispatch, how built-in lists repeat themselves, the shared-reference trap that comes with repetition, and how to write a safe in-place hook.

The *= dispatch

a *= b is evaluated as a = type(a).__imul__(a, b). The hook changes the object and its return value is bound back to the name. The trace below shows one call per operation.

basic_imul.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __imul__(self, other):
        print("__imul__", self, "*", other)
        self.x *= other
        self.y *= other
        return self

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v = Vector(2, 3)
v *= 4
v *= 2
print(v)

Each call scales both components and returns the same Vector. The multiplication is applied in sequence: 2 × 4 × 2 gives 16, and 3 × 4 × 2 gives 24.

$ python basic_imul.py
__imul__ Vector(2, 3) * 4
__imul__ Vector(8, 12) * 2
Vector(16, 24)

Lists repeat, tuples are rebound

A list implements __imul__ by extending itself, so aliases see the repeated elements. A tuple has no such hook; *= falls back to __mul__ and rebinds the name to a new tuple.

list_tuple_imul.py
a = [1, 2]
alias = a
a *= 3
print(a, alias, a is alias)

t = (1, 2)
talias = t
t *= 3
print(t, talias, t is talias)

The list kept its identity, which is why alias shows six elements. The tuple operation is equivalent to t = t * 3; the alias still holds the original two-element tuple.

$ python list_tuple_imul.py
[1, 2, 1, 2, 1, 2] [1, 2, 1, 2, 1, 2] True
(1, 2, 1, 2, 1, 2) (1, 2) False

Fallback to __mul__

A class without __imul__ gets a = a * b when written with *=. This is the right choice for immutable objects, which cannot update themselves.

fallback_mul.py
class Frozen:
    def __init__(self, value):
        self.value = value

    def __mul__(self, other):
        print("__mul__")
        return Frozen(self.value * other)

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


f = Frozen(3)
alias = f
f *= 4
print(f, alias, f is alias)

The fallback built a new object and rebound f. The alias is unchanged, so no shared reference is affected. Implement __mul__ alone whenever your object is immutable.

$ python fallback_mul.py
__mul__
Frozen(12) Frozen(3) False

The operator.imul function

operator.imul(a, b) performs the hook call without rebinding a variable in the caller's scope. For mutable operands it returns the object that was changed.

operator_imul.py
import operator


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __imul__(self, other):
        self.x *= other
        self.y *= other
        return self

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v = Vector(2, 3)
same = operator.imul(v, 4)
print(v, same, v is same)
print(operator.imul([1, 2], 3))

Both the custom vector and the built-in list are mutable, so the function returns an object that already contains the result. With immutable operands you must assign the returned value yourself.

$ python operator_imul.py
Vector(8, 12) Vector(8, 12) True
[1, 2, 1, 2, 1, 2]

Scalar and component-wise scaling

An __imul__ hook can accept different kinds of multiplier. Here a number scales every component, while another vector scales them component by component.

vector_scaling.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __imul__(self, other):
        if isinstance(other, Vector):
            self.x *= other.x
            self.y *= other.y
        else:
            self.x *= other
            self.y *= other
        return self

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v = Vector(2, 3)
v *= Vector(4, 5)
print(v)
v *= 2
print(v)

The first operation multiplies x by 4 and y by 5. The second scales both results by 2. Because the object is mutated, any other name referring to v observes both changes.

$ python vector_scaling.py
Vector(8, 15)
Vector(16, 30)

The shared-rows pitfall

Multiplying a list repeats references, not copies. A grid built with * therefore shares its rows: changing one row changes them all. A custom __imul__ can avoid this by copying each row.

shared_rows.py
row = [0] * 3
grid = [row] * 3
print(grid)
grid[0][1] = 7
print(grid)
print(grid[0] is grid[1])


class Grid:
    def __init__(self, rows):
        self.rows = [list(r) for r in rows]

    def __imul__(self, factor):
        self.rows = [list(row) for row in self.rows
                     for _ in range(factor)]
        return self

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


g = Grid([[0, 0, 0]])
g *= 3
print(g)
g.rows[0][1] = 7
print(g)
print(g.rows[0] is g.rows[1])

The plain list repeats the same row object three times, so one assignment appears in every row. The Grid hook builds a fresh list for each copy, the rows are distinct, and only the first one changes. Even a custom hook must be careful: writing self.rows *= factor would have reproduced the same bug.

$ python shared_rows.py
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 7, 0], [0, 7, 0], [0, 7, 0]]
True
Grid([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
Grid([[0, 7, 0], [0, 0, 0], [0, 0, 0]])
False

Validating the multiplier

Check the operand before changing state. Unsupported types should return NotImplemented, while a value that is never valid for the class can raise an exception.

validate_imul.py
class Scaled:
    def __init__(self, value):
        self.value = value

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

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


s = Scaled(3)
s *= 4
print(s)
for bad in (-1, 1.5):
    try:
        s *= bad
    except (ValueError, TypeError) as e:
        print(type(e).__name__, e)
print(s)

A negative factor raises ValueError; a float makes the hook decline and Python raises TypeError. Neither attempt changed s.value, which still holds 12.

$ python validate_imul.py
Scaled(12)
ValueError factor must not be negative
TypeError unsupported operand type(s) for *=: 'Scaled' and 'float'
Scaled(12)

Best practices

A few rules keep in-place multiplication predictable:

Source

object.__imul__ - Python documentation

Emulating numeric types - Python documentation

operator.imul - Python documentation

Common sequence operations - Python documentation

In this article we have implemented the __imul__ method. We have covered the *= dispatch, the fallback to __mul__, sequence repetition, shared rows, validation, and scaling. For related topics, see Python __mul__ method, Python __iadd__ method, and copy by value vs copy by reference.

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.