Course contentsShow
← Python
Lesson 303 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Implementing Custom Iterators with Dunder Methods

Define custom classes using __iter__ and __next__ protocols to create stateful objects that behave like built-in generator sequences.

In this lesson, you will learn how to create your own custom objects that behave like built-in sequences by implementing the __iter__ and __next__ dunder methods.

The Iterator Protocol

Python's iteration system relies on the iterator protocol. For an object to be considered an "iterator," it must satisfy two requirements:

  1. It must implement __iter__(), which returns the iterator object itself.
  2. It must implement __next__(), which returns the next item in the sequence. When there are no more items, it must raise the StopIteration exception to signal the end.

By defining these methods, you create a stateful object that remembers its progress through a sequence without needing to store the entire collection in memory.

Creating a Custom Counter

Consider this class that generates a countdown sequence:

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

# Using the custom iterator
timer = Countdown(3)
for count in timer:
    print(count)

In the example above, the __iter__ method returns self, allowing the object to be used in loops or with the next() function. Every time the loop requests a value, __next__ is triggered. It checks if the sequence is finished; if not, it decrements the self.current state and returns the value. Once self.current hits zero, StopIteration is raised, gracefully ending the loop.

This pattern is highly memory-efficient because it calculates values on the fly rather than pre-generating a list. It gives you full control over the internal state of your sequence while maintaining the familiar interface of Python's built-in iterables.

Key Takeaway: By implementing __iter__ and __next__, you turn your classes into custom, stateful generators that integrate seamlessly with Python’s iteration syntax.