How do __iadd__ and other in-place operator methods (__isub__, __imul__) differ from their non-in-place counterparts?
Short answer
__iadd__(self, other) implements the += operator and can mutate self in place and return self, avoiding creating a new object (unlike __add__, which must return a new object).
Advertisement
AModel answer
__iadd__(self, other) implements the += operator and can mutate self in place and return self, avoiding creating a new object (unlike __add__, which must return a new object). If __iadd__ isn't defined, Python falls back to __add__ followed by reassignment (x = x + y), which is less efficient for mutable, resizable containers.
class Bag:
def __init__(self, items=None):
self.items = items or []
def __iadd__(self, other):
self.items.extend(other)
return self # mutate and return self
b = Bag([1,2])
b += [3,4]
print(b.items) # [1,2,3,4]Real-world example
A custom mutable Matrix class implements __iadd__ so accumulating large matrices with += avoids allocating a brand-new matrix object on every update, improving performance in tight loops.
Likely follow-ups
- What happens if __iadd__ returns a different object than self?
- Why do immutable types typically not define __iadd__?
Related topics