Sub topic 4
Building an Iterator Class by Hand
This chapter assumes you can write Python classes with __init__ and other special methods, and that you know the idea behind the iterator protocol from the previous chapters: iter() produces an iterator, and next() pulls values from it until StopIteration. Here you implement that protocol yourself. You will see where the state belongs, why a one-class design is single-use, how to split an iterable from its iterator, and which mistakes cause confusing errors.
What the class must provide
An iterator is any object with two methods:
__next__(self)returns the next value, or raisesStopIterationwhen there are no more values.__iter__(self)returns the iterator itself.
The second method looks redundant, but it is required. A for loop calls iter() on whatever it is given, and iter() calls __iter__. If iterators did not return themselves from __iter__, you could not pass an iterator to a for loop, to list(), or to any other function that expects an iterable.
The class also needs somewhere to store its position. Each call to __next__ reads that state, produces a value, and updates the state.
A first iterator: Countdown
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]Follow the order of operations in __next__:
- Check whether the sequence is finished. If so, raise
StopIteration. - Save the value to return in a local variable.
- Update the state so the next call produces the following value.
- Return the saved value.
Step 2 matters because you must change self.current before returning, and a return ends the method. Saving the value first lets you update the state and still return the old one.
list() does the same work a for loop does. It calls iter() once, then calls __next__ repeatedly and catches StopIteration as the signal to stop.
Where the state lives
All the iteration state is in instance attributes. In Countdown that is self.current. Two separate Countdown objects have independent state, so they do not interfere:
a = Countdown(2)
b = Countdown(2)
print(next(a)) # 2
print(next(a)) # 1
print(next(b)) # 2The state is also what makes the object single-use. After a has produced 2 and 1, a.current is 0, and it stays 0. Nothing resets it.
it = Countdown(1)
print(next(it)) # 1
for _ in range(2):
try:
next(it)
except StopIteration:
print("stop")
# stop
# stopThis output shows a rule of the protocol: once an iterator raises StopIteration, it must keep raising it on every later call. Code that consumes iterators relies on this. A well-behaved iterator never "wakes up" and produces values again after finishing. Because Countdown never increases current after it reaches zero, it follows the rule.
A more realistic iterator: batches
Counting down is only a demonstration. Here is an iterator that does something you might need: it splits a sequence into fixed-size chunks.
class Batches:
def __init__(self, items, size):
if size < 1:
raise ValueError("size must be at least 1")
self.items = items
self.size = size
self.position = 0
def __iter__(self):
return self
def __next__(self):
if self.position >= len(self.items):
raise StopIteration
batch = self.items[self.position:self.position + self.size]
self.position += self.size
return batch
print(list(Batches([1, 2, 3, 4, 5], 2))) # [[1, 2], [3, 4], [5]]Two details are worth noticing. The constructor validates its argument, so the error appears when you create the object and not in the middle of a loop. The last batch is shorter than size, because slicing past the end of a list is safe.
This version still requires items to support len() and slicing. It would fail on another iterator. Writing an iterator that wraps another iterator is possible, and the generator chapters show a much shorter way to do it.
Separating the iterable from the iterator
An object that returns self from __iter__ is its own iterator, so it can be traversed only once. That is fine for streams such as a network connection, but surprising for something that feels like a collection. If you want an object you can loop over many times, use two classes:
- The iterable holds the data or the parameters. Its
__iter__returns a new iterator each time. - The iterator holds the position and implements
__next__.
class CountdownRange:
def __init__(self, start):
self.start = start
def __iter__(self):
return _CountdownIterator(self.start)
class _CountdownIterator:
def __init__(self, current):
self.current = current
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
c = CountdownRange(3)
print(list(c)) # [3, 2, 1]
print(list(c)) # [3, 2, 1]CountdownRange has no __next__, so it is an iterable but not an iterator. next(c) would raise TypeError. Every loop creates its own _CountdownIterator, so loops do not share a position, and even nested loops over the same CountdownRange work independently.
Built-in types follow this design. A list is an iterable, and iter(my_list) gives a separate list_iterator object each time.
Choose the design by asking whether callers will expect to loop more than once. Use the two-class split for collection-like objects. Use the single class for one-shot streams.
Common errors and edge cases
A few mistakes come up repeatedly when writing iterators by hand.
| Mistake | Symptom | Fix |
|---|---|---|
| Defining `__next__` but not `__iter__` | `TypeError: '...' object is not iterable` in a `for` loop | Add `def __iter__(self): return self` |
| Returning `None` at the end instead of raising | The loop never ends, or `None` values appear in results | Raise `StopIteration` explicitly |
| Resetting state inside `__iter__` of a single class | Two loops over the same object restart each other | Use the iterable/iterator split |
| Updating state after `return` | The state never changes, so the loop runs forever | Save the value, update the state, then return |
| Producing values again after `StopIteration` | Consumers behave unpredictably | Keep state so that finished stays finished |
The first row is easy to reproduce:
class Broken:
def __next__(self):
raise StopIteration
try:
for x in Broken():
pass
except TypeError as e:
print(e) # 'Broken' object is not iterableThe object has __next__, so next() would work on it. The for loop fails because it calls iter() first, and iter() needs __iter__.
Resetting state in __iter__ deserves a closer look, because it appears to work in simple tests. If you write def __iter__(self): self.current = self.start; return self, then list(obj) works twice in a row. But it is a trap. Two loops that overlap, such as nested loops over the same object or zip(obj, obj), share one current attribute, and calling iter() again silently rewinds the loop already in progress. The two-class split avoids this.
There are two more edge cases:
- Infinite iterators are legal. A
__next__that never raisesStopIterationis a valid iterator. Do not calllist()on it. Useitertools.isliceto take a bounded slice, which you will meet later in this tutorial. - Do not let a stray
StopIterationescape. If your__next__callsnext()on another iterator and that one runs out, itsStopIterationpropagates out of your method. In an iterator class that usually does what you want, because your iterator ends too. But if you did not intend the end of iteration, the loop stops silently and hides a bug. Catch it and decide on purpose.
Why generators come next
The hand-written class has real costs. For Countdown, you wrote about a dozen lines to express "count from start down to 1". Most of it is protocol boilerplate: __iter__ returning self, saving a value before updating state, and raising StopIteration by hand. The part that carries the logic is two or three lines.
Writing iterators as classes is still worth knowing. It is the right tool when the iterator needs several methods beyond __next__, such as reset() or peek(), or when you need to expose attributes like the current position. It also shows exactly what Python does for you when you write a generator, which is the subject of the next chapter.
Exercise
Why does list(it) return an empty list the second time you call it on the single-class Countdown(3) object it, and what is the smallest change that lets the same object be listed twice with the same result?
Show answer
The first call exhausts the iterator: self.current ends at 0 and never changes again, so every later __next__ raises StopIteration immediately and list() returns []. The smallest correct change is to split the class into an iterable that stores start and an iterator that stores the position, as in CountdownRange and _CountdownIterator. Then __iter__ on the iterable returns a new iterator each time. Resetting self.current inside __iter__ also makes two sequential list() calls work, but it breaks overlapping loops over the same object.
Exercise
Write an iterator class Every that takes a list items and an integer step, and yields items[0], items[step], items[2*step], and so on. Then show the output of list(Every([10, 20, 30, 40, 50], 2)).
Show answer
class Every:
def _init(self, items, step):
if step < 1:
raise ValueError("step must be at least 1")
self.items = items
self.step = step
self.position = 0
def iter(self):
return self
def next_(self):
if self.position >= len(self.items):
raise StopIteration
value = self.items[self.position]
self.position += self.step
return value
The call list(Every([10, 20, 30, 40, 50], 2)) returns [10, 30, 50]. The position moves 0, 2, 4, then 6, which is past the end, so StopIteration is raised.