Custom Iterators in Python
Advanced Iteration
Iterator Protocol Deep Dive
Every for-loop depends on the iterator protocol. Build your own iterable objects and unlock streaming patterns.
Protocol
class Countdown:
def __init__(self, start: int):
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
__iter__returns the iterator (oftenself).__next__raisesStopIterationto end the loop.
Yield from objects
Even if you don’t implement __next__, returning an iterator from __iter__ makes your object iterable:
class LessonPlan:
def __init__(self, topics):
self.topics = topics
def __iter__(self):
return iter(self.topics)