Course contentsShow
← Python
Lesson 450 of 1,0607. Object-Oriented ProgrammingFree lesson

Enabling In-place Assignment Operators

Implement augmented assignment methods such as __iadd__ to optimize memory usage when modifying objects with operators like += or -=

In this lesson, you will learn how to optimize your custom objects by implementing in-place assignment operators like += and -=.

The Efficiency of In-place Assignment

When you use an operator like += on an object, Python typically creates a brand-new object to hold the result. For example, if you have a class representing a large data structure, my_obj += 5 would normally create a new instance, copy the old data over, add the 5, and discard the old instance. This is memory-intensive.

To avoid this, Python allows us to implement "augmented assignment" methods. By defining __iadd__, __isub__, and similar methods, you tell Python to perform the operation directly on the existing object, modifying its internal state rather than creating a copy.

Implementing __iadd__

When you implement __iadd__, your method should perform the calculation and then return self. This return value is crucial because it allows the assignment statement to work correctly.

Consider a simple Counter class:

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

    def __iadd__(self, other):
        self.value += other
        # Return self so the object updates itself in place
        return self

c = Counter(10)
c += 5  # This triggers __iadd__
print(c.value)  # Output: 15

Why It Matters

If you do not define __iadd__, Python will fall back to the standard __add__ method. It will calculate the result, create a new object, and reassign your variable name to that new object. By defining the in-place version, you keep your memory usage lean, especially when dealing with objects that hold heavy data like matrices or large lists.

Always remember that these methods are expected to modify the current instance and return it. This keeps your code clean, readable, and highly efficient under the hood.

Key Takeaway: Implementing __iadd__ and its siblings allows your objects to be updated in memory without the overhead of creating redundant new instances.