Course contentsShow
← Python
Lesson 627 of 1,06010. Advanced Language FeaturesFree lesson

Implementing the Iterator Protocol with Dunder Methods

You will create custom iterable objects by implementing the __iter__ and __next__ methods to control the traversal logic of your data structures.

In this lesson, you will learn how to make your custom objects loopable by implementing the __iter__ and __next__ dunder methods.

The Iterator Protocol

In Python, any object that adheres to the "Iterator Protocol" can be used in a for loop. To make your custom class an iterator, you need to implement two specific methods:

  1. __iter__: This method must return the iterator object itself. It allows the object to be compatible with loops.
  2. __next__: This method returns the next item in the sequence. When there are no more items to return, it must raise the StopIteration exception to signal the end of the loop.

A Practical Example

Imagine we want a custom class that behaves like a countdown timer. We can control exactly how the state changes during each step of the iteration:

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        
        value = self.current
        self.current -= 1
        return value

# Usage:
for number in Countdown(3):
    print(number) # Output: 3, 2, 1

How it Works

When you pass an instance of Countdown to a for loop, Python calls __iter__ to retrieve the iterator. Then, it repeatedly calls __next__ on that iterator. The loop continues gracefully until your code raises StopIteration.

By defining these methods, you transition from simply storing data to controlling the logic of how that data is consumed. You aren't just holding a collection; you are defining the "behavior" of the traversal itself. This is particularly powerful when dealing with infinite data streams, lazy loading, or complex data structures where you don't want to load every element into memory at once.

Key Takeaway: Implementing __iter__ and __next__ allows your custom objects to define their own iteration logic, enabling them to be used seamlessly in standard Python looping constructs.