Sub topic 10
In-place operators and mutability
This chapter assumes you can write classes with __init__ and __repr__. It also assumes you know __add__ and NotImplemented from the arithmetic and reflected-operator chapters, and that you know the difference between mutable objects (lists, dicts) and immutable ones (tuples, strings, numbers).
What `x += y` really does
An augmented assignment such as x += y is not just shorthand for x = x + y. Python tries these steps in order:
- Call
type(x).__iadd__(x, y)if the method exists. Whatever it returns is bound to the namex. - If
__iadd__is missing, or it returnsNotImplemented, evaluatex + ywith the normal binary rules. That means__add__, then the reflected__radd__ony. - Bind the result to
x.
The step that surprises people is that the name is always rebound to the return value. The in-place method does not have to return self, but it almost always should.
The in-place method family
Every binary operator has an in-place partner named by inserting i after the leading underscores.
| Statement | Method | Fallback | Column |
|---|---|---|---|
| `x += y` | `__iadd__` | `__add__`, `__radd__` | |
| `x -= y` | `__isub__` | `__sub__`, `__rsub__` | |
| `x *= y` | `__imul__` | `__mul__`, `__rmul__` | |
| `x /= y` | `__itruediv__` | `__truediv__`, `__rtruediv__` | |
| `x //= y` | `__ifloordiv__` | `__floordiv__`, `__rfloordiv__` | |
| `x %= y` | `__imod__` | `__mod__`, `__rmod__` | |
| `x **= y` | `__ipow__` | `__pow__`, `__rpow__` | |
| `x @= y` | `__imatmul__` | `__matmul__`, `__rmatmul__` | |
| `x &= y`, `x \ | = y`, `x ^= y` | `__iand__`, `__ior__`, `__ixor__` | the matching binary methods |
| `x <<= y`, `x >>= y` | `__ilshift__`, `__irshift__` | the matching binary methods |
Immutable classes: do nothing
If your objects are immutable, you should not define any in-place methods. The fallback gives the correct behavior: v += w builds a new object and rebinds v. The earlier Vector has only __add__, and it already supports +=:
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)
v = Vector(1, 2)
alias = v
v += Vector(3, 4)
print(v) # Vector(4, 6)
print(alias) # Vector(1, 2)
print(v is alias) # FalseThe alias keeps the old value because += created a new object. This is the same behavior as int and str.
Mutable classes: modify and return self
A mutable container can often do better than the fallback. Building a fresh object for every += copies all the data, which makes a loop that appends many times quadratic. An __iadd__ that updates the existing object avoids the copy.
class Stack:
def __init__(self, items=()):
self.items = list(items)
def __repr__(self):
return f'Stack({self.items!r})'
def __add__(self, other):
if not isinstance(other, Stack):
return NotImplemented
return Stack(self.items + other.items)
def __iadd__(self, other):
if not isinstance(other, Stack):
return NotImplemented
self.items.extend(other.items)
return self
a = Stack([1, 2])
alias = a
a += Stack([3])
print(a) # Stack([1, 2, 3])
print(alias) # Stack([1, 2, 3])
print(a is alias) # True
b = a + Stack([4])
print(b) # Stack([1, 2, 3, 4])
print(b is a) # False
print(a) # Stack([1, 2, 3])a += ... changed the object that alias also refers to. a + ... left a alone and returned a new Stack. Built-in lists behave the same way, and users of a mutable class expect it.
Always return a value
The most common bug is forgetting the return. Python rebinds the name to whatever comes back, and a function with no return gives back None.
class Total:
def __init__(self):
self.n = 0
def __iadd__(self, amount):
self.n += amount # missing: return self
t = Total()
t += 5
print(t) # NoneThe object was updated, but t no longer refers to it. The error shows up later, usually as AttributeError: 'NoneType' object has no attribute 'n', far from the real cause.
Return NotImplemented for unsupported types
Use the same rule as for binary operators: if you do not know how to handle other, return NotImplemented. Python then falls back to __add__ and __radd__, and finally raises a clear TypeError. Raising an exception yourself would skip the fallback and block types that could have handled the operation through a reflected method.
Keeping the two forms consistent
a += b and a = a + b should produce equal values. They differ only in whether the original object is modified. When you implement both, a simple way to keep them consistent is to write the in-place form once and build the binary form from a copy:
class Bag:
def __init__(self, items=()):
self.items = list(items)
def __repr__(self):
return f'Bag({self.items!r})'
def __iadd__(self, other):
if not isinstance(other, Bag):
return NotImplemented
self.items.extend(other.items)
return self
def __add__(self, other):
if not isinstance(other, Bag):
return NotImplemented
result = Bag(self.items)
result += other
return result
x = Bag([1])
y = x + Bag([2])
print(x, y) # Bag([1]) Bag([1, 2])The copy in __add__ is essential. If __add__ called self.__iadd__(other) directly, then x + y would silently change x.
Gotchas with built-in types
The in-place rules explain several behaviors of built-in types.
- Lists accept any iterable in
+=, but not in+.list.__iadd__behaves likeextend, sonums += 'ab'appends the characters'a'and'b'.nums + 'ab'raisesTypeError. If you copy list behavior, decide deliberately whether your__iadd__is that permissive. - Aliases see in-place changes. If a function receives a list and does
items += [0], the caller's list changes. Withitems = items + [0], it does not. A tuple has no__iadd__, so+=on a tuple always makes a new tuple. - A mutable object inside a tuple. The statement
t[0] += yis a get, an in-place operation, and then a set back into the tuple. The in-place step succeeds, and the final set fails:
t = ([1], 2)
try:
t[0] += [3]
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
print(t) # ([1, 3], 2)The error is raised, yet the list was already extended.
When to define in-place methods
- Define them for mutable containers where an in-place update is cheaper than copying, and where users expect aliasing, as with
list,setanddict. - Skip them for immutable value types such as vectors, money and versions. The fallback already does the right thing.
- Do not mix semantics. If
+=mutates, document it, and do not make it return a different object. - Mutable objects defined with
__eq__should not be hashable, because an in-place change would alter their hash while they sit in a set. Set__hash__ = Nonefor those classes.
Exercise
Given this class, what does the following code print, and what single change fixes it? class Counter: def _init(self): self.n = 0 def iadd_(self, k): self.n += k c = Counter() c += 2 print(c)
Show answer
It prints None. c += 2 rebinds c to the return value of __iadd__, and the method has no return statement, so it returns None. Adding return self at the end of __iadd__ fixes it, so c keeps referring to the updated Counter.
Exercise
A class defines __add__ but not __iadd__. Does x += y work? Does it modify the object that x referred to?
Show answer
Yes, it works. Python falls back to x + y and rebinds x to the new object. The original object is not modified, so any other name referring to it still sees the old value.