How to Create an Iterator Class with Dunder Methods in Python
A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.
Python code
20 linesclass Counter:
def __init__(self, start=0, end=5):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += 1
return value
if __name__ == "__main__":
counter = Counter(1, 5)
for num in counter:
print(num)
Output
1
2
3
4
How it works
The __iter__ method returns self, making the object its own iterator, which is required for any iterator. __next__ contains the loop logic: it checks the current value against the end, raises StopIteration when exhausted, otherwise returns the current value and increments it. The class is also an iterable, so it works directly in a for loop. This pattern is flexible and can be extended with custom logic or additional state.
Common mistakes
- Forgetting to increment the current value inside __next__
- Not raising StopIteration, causing an infinite loop
- Missing __iter__ that returns self, making `for` loops fail
Variations
- Use a generator function with `yield` for a simpler iterator
- Inherit from collections.abc.Iterator to enforce the protocol
Real-world use cases
- Custom sequence generators for paginated API clients that fetch data chunk by chunk.
- Lazy-loaded file parsers that yield records one at a time without loading all into memory.
- Stateful iterators for game loops or simulation steps that maintain internal counters.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.