What is the relationship between generators and the iterator protocol?
Short answer
Every generator object automatically implements the iterator protocol -- it has __iter__ (returning itself) and __next__ (resuming execution until the next yield or StopIteration on completion).
Advertisement
AModel answer
Every generator object automatically implements the iterator protocol -- it has __iter__ (returning itself) and __next__ (resuming execution until the next yield or StopIteration on completion). Generators are the easiest way to write an iterator without manually managing state in a class.
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen), next(gen)) # 3 2
print(hasattr(gen, '__next__')) # TrueReal-world example
A recursive directory walker is written as a generator function instead of a class-based iterator because yield handles the state machine automatically.
Likely follow-ups
- Why is a generator function simpler than a class-based iterator for most cases?
- What state does a generator preserve between yields?
Related topics