In this lesson, you will learn how to manually control the lifecycle of an iterator by raising the StopIteration exception to signal that a sequence has reached its end.
The Iterator Protocol Mechanics
As you learned in the previous lesson, the iterator protocol relies on the __next__ method. When you call next() on an iterator, it performs its logic and returns a value. But how does Python know when to stop? The for loop, which consumes these iterators, is designed to catch a specific signal: the StopIteration exception.
When your custom iterator runs out of elements to yield, raising this exception is the standard way to tell the caller that the sequence is exhausted.
Controlling the Flow
Consider a simple counter that stops once it reaches a defined limit:
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(2):
print(number)
# Output: 2, 1, 0
Why Raise an Exception?
In Python, StopIteration is not treated as a "failure" in the traditional sense; it is a communication tool. By raising it, you are explicitly telling the iteration machinery that there is no further state to process. If you don't raise it, the iterator might attempt to return None indefinitely or enter an infinite loop if the caller doesn't know how to interpret the results.
When you raise StopIteration, the for loop catches it internally and terminates the loop gracefully. This mechanism is the engine behind how Python handles sequences, and it provides a clean, language-standard way to manage your custom state transitions.
Key Takeaway: Raising StopIteration is the standard, protocol-compliant way to signal the completion of an iterator, allowing the Python runtime to gracefully terminate the iteration process.