Sub topic 10
In-place operators and mutability
This chapter assumes you know __add__ and NotImplemented from the previous chapters, and that you understand the difference between mutable and immutable objects.
What `+=` really does
An augmented assignment such as a += b first looks for __iadd__ on the type of a. If that method exists, Python calls it and binds the result to the name a. If the method is missing, or it returns NotImplemented, Python falls back to a = a + b, which uses __add__ and then the reflected __radd__ on b.
The other operators follow the same pattern: __isub__, __imul__, __itruediv__, and so on.
Mutating versus rebinding
The difference matters when two names refer to the same object. An in-place method changes the object, so every name sees the change. A fallback to __add__ creates a new object and rebinds only one name.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
class MutableVector(Vector):
def __iadd__(self, other):
if not isinstance(other, Vector):
return NotImplemented
self.x += other.x
self.y += other.y
return self
a = Vector(1, 2)
alias = a
a += Vector(10, 10) # falls back to a = a + ...
print(a, alias) # Vector(11, 12) Vector(1, 2)
m = MutableVector(1, 2)
alias = m
m += Vector(10, 10) # mutates in place
print(m, alias) # Vector(11, 12) Vector(11, 12)
print(m is alias) # TrueBuilt-in types behave the same way. list defines __iadd__, so += extends the list in place. tuple and int do not, so += rebinds the name.
Common errors
- Mutating an immutable type. If your class is hashable or meant to be a value, as with the
Vectorthat defines__hash__, leave out__iadd__. The fallback then gives the safe behavior. - Returning a new object from
__iadd__. This works, but it defeats the purpose and surprises readers who expect mutation. - Inconsistent results.
a += banda = a + bshould produce equal values. They differ only in whether the object is changed or replaced. - Items inside tuples. The assignment step still runs after
__iadd__, so the mutation happens before the error:
t = ([1],)
try:
t[0] += [2]
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
print(t) # ([1, 2],)Summary of rules
| Situation | Define `__iadd__`? |
|---|---|
| Mutable container or accumulator | Yes, mutate and return `self` |
| Immutable value object | No, let Python fall back to `__add__` |
| Operand type not supported | Return `NotImplemented` |
Exercise
A class defines __add__ but not __iadd__. Given x = Obj(); y = x; x += Obj(), does y see the change? Why?
Show answer
No. With no __iadd__, Python evaluates x = x + Obj(). __add__ returns a new object that is bound to x. The name y still refers to the original object, which is unchanged.