In this lesson, you’ll learn how to make your custom Python objects compatible with for loops by implementing the iterator protocol.
Why Make Objects Iterable?
When you use a for loop on a list or a range, Python is secretly calling specific methods behind the scenes to fetch items one by one. By defining these same methods in your own class, you can create custom collections—like a class that tracks a sequence of sensor readings or a custom database cursor—that behave exactly like built-in Python collections.
The Iterator Protocol
To make an object iterable, you must implement two magic methods:
__iter__: This method returns the "iterator" object itself. Often, you simplyreturn self.__next__: This method returns the next item in the sequence. When there are no items left, it must raise theStopIterationexception, which tells theforloop that the iteration is finished.
A Concrete Example
Imagine we want a class that counts down from a specific number to zero:
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 our custom iterable
for number in Countdown(3):
print(number)
In the example above, the for loop calls __iter__ once to get the iterator, and then repeatedly calls __next__. When current drops below zero, we raise StopIteration, signaling the loop to terminate gracefully.
Without these methods, trying to use your object in a for loop would trigger a TypeError: 'MyClass' object is not iterable. By defining this protocol, you provide a standard interface for other developers to interact with your data structures naturally, keeping your code "Pythonic" and clean.
Key Takeaway: By implementing __iter__ and __next__, you empower your objects to work seamlessly with Python’s powerful iteration tools like for loops and comprehensions.