Sub topic 4
Building an iterator class by hand
This chapter assumes you know Python classes, special (dunder) methods, loops, and try/except. It also assumes you have seen that an iterator is an object with __iter__ and __next__. Here you write one yourself and learn where hand-written iterators usually go wrong.
Why write one by hand
Generators (covered in the next chapter) are shorter for most jobs. A class is still worth knowing, because it shows exactly what Python requires of an iterator. It is also the right tool when an iterator needs extra methods, public attributes, or state you want to inspect from outside.
An iterator class needs two things:
__iter__returns the iterator itself (return self).__next__returns the next value, or raisesStopIterationwhen there are no more values.
A countdown iterator
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
print(list(Countdown(3))) # [3, 2, 1]__init__ stores the position in self.current. Each call to __next__ reads that position, moves it, and returns the old value. When the counter reaches zero, __next__ raises StopIteration. list() catches that exception and stops collecting.
The for loop uses the same calls:
for n in Countdown(3):
print(n)The loop calls iter() on the object, which calls __iter__. It then calls __next__ repeatedly until StopIteration is raised.
Tracing the calls
The state lives in the object
The iterator keeps its position in self.current. That has a consequence you must plan for. Once the iterator is used up, it stays used up.
c = Countdown(2)
print(list(c)) # [2, 1]
print(list(c)) # []The second list(c) is empty because self.current is already 0. Nothing resets it. Iterators are single-use by design.
Making a reusable iterable
If you want an object you can loop over many times, separate the two roles. The container is an iterable. It hands out a new iterator each time __iter__ is called.
class CountdownRange:
def __init__(self, start):
self.start = start
def __iter__(self):
return Countdown(self.start)
r = CountdownRange(3)
print(list(r)) # [3, 2, 1]
print(list(r)) # [3, 2, 1]CountdownRange has no __next__, so it is an iterable and not an iterator. Each for loop gets its own fresh Countdown, so loops do not interfere with each other. Built-in lists work this way.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting `__iter__` on the iterator | `for` raises `TypeError: 'Countdown' object is not iterable` | Add `def __iter__(self): return self` |
| Returning `None` instead of raising at the end | The loop never ends, because `None` is a valid value | Raise `StopIteration` |
| Using `return` for the end signal | Same infinite loop | Raise `StopIteration` explicitly |
| Updating state after `return` | The update never runs | Save the value first, update state, then return |
| Reusing an exhausted iterator | Empty results, no error | Create a new iterator or use an iterable class |
Exercise
Write an iterator class Evens that takes a limit and produces the even numbers from 0 up to but not including limit. What does list(Evens(7)) return?
Show answer
class Evens: def _init(self, limit): self.limit = limit self.current = 0 def iter(self): return self def next_(self): if self.current >= self.limit: raise StopIteration value = self.current self.current += 2 return value list(Evens(7)) returns [0, 2, 4, 6].
Exercise
Why does looping over a Countdown(3) object twice print nothing the second time, but looping over a CountdownRange(3) object twice works both times?
Show answer
Countdown is an iterator, so its position is stored in the object and is used up after one loop. CountdownRange is an iterable that returns a new Countdown from __iter__ on each loop, so every loop starts from the beginning.